快速API代码
这将是您的终点。
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/file")
async def upload_file(file: UploadFile = File(...)):
# Do here your stuff with the file
return {"filename": file.filename}
JavaScript 代码
这是您的 javascript 代码(假设您使用 javascript 上传文件)
form = new FormData();
form.append("file", myFile);
let response = await fetch('/file', {
method: 'POST',
body: form
});
let result = await response.json();
编辑:Python文件上传
我在用着httpx
,但从技术上讲它应该完全兼容requests
.
import httpx
# Create a dict with a key that has the same name as your file parameter and the file in binary form (the "b" in "rb")
f = {'file': open('foo.png', 'rb')}
r = httpx.post("your_url/file", files=f)
您可以在官方文档中查看更多配置/示例httpx
at https://www.python-httpx.org/quickstart/#sending-multipart-file-uploads.
再说一遍,我没有测试代码,因为我现在时间很紧。
编辑结束
请注意,文件的参数名称必须与用于发送文件的参数名称相匹配。
以防万一,我还有另一个关于如何使用 POSTMAN 测试它的答案。看如何使用 postman 将文件发送到 fastapi 端点
NOTE
我没有测试代码,因为我现在没有时间。以防万一,还有一个与我之前的答案相关的链接也有效(除非 FASTAPI 引入了重大更改)。