Fastapi有上传多个文件的接口代码,亲测可用。缺点是:使用浏览器接口文档操作比较方便,如果客户端没有浏览器,使用python写的代码来上传文件,则调了很久都调不成功。Fastapi官方链接:Fastapi官方上传多文件链接
官方核心代码如下:
from typing import List
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in files]}
自己写失败的客户端代码:
import requests
url = "http://127.0.0.1:8000/uploadfiles/"
path_file0 = r'F:\Eby\Project\my_super_project\sql_app\test_image\c3\new_00004_1_0.jpg'
path_file1 = r'F:\Eby\Project\my_super_project\sql_app\test_image\c3\new_00004_1_1.jpg'
files = {"files":[open(path_file0,'rb'),open(path_file1,'rb')}
result = requests.post(url=url, files=files)
print(result.text)
主要是files的格式与服务端需要的格式总是对不上,导致上传失败。就算换着花样写files还是失败,如:
files = [{"file0":[open(path_file0,'rb')},{"file1":open(path_file1,'rb')}]
files = {("files":[open(path_file0,'rb')),("files":[open(path_file1,'rb'))}
...
全都失败,谁写谁知道。
经过多番尝试,终于试出正确的服务器接口代码与客户端代码。
服务器代码:
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/uploadfiles/")
async def create_upload_files(file0: UploadFile = File(...),file1:UploadFile = File(...)):
return {"filenames": [file0.filename,file1.filename]}
客户端代码:
import requests
url = "http://127.0.0.1:8000/uploadfiles/"
path_file0 = r'F:\Eby\Project\my_super_project\sql_app\test_image\c3\new_00004_1_0.jpg'
path_file1 = r'F:\Eby\Project\my_super_project\sql_app\test_image\c3\new_00004_1_1.jpg'
files = {'file0':open(path_file0,'rb'),'file1':open(path_file1,'rb')}
result = requests.post(url=url, files=files)
print(result.text)
最终调试成功。