如何使用FastAPI上传文件?
问题:
当使用FastAPI上传文件时根据官方文档,file2store变量仍然存在空。
原因:
解决方案:
app. py:
from fastapi import File, UploadFile @app.post("/create_file") def create_file(file: UploadFile = File(...)): try: contents = file.file.read() # store contents to the database except Exception: return {"message": "Error uploading file"} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}"}
替代对于异步端点:
@app.post("/create_file") async def create_file(file: UploadFile = File(...)): try: contents = await file.read() # store contents to the database except Exception: return {"message": "Error uploading file"} finally: await file.close() return {"message": f"Successfully uploaded {file.filename}"}
上传多个文件:
from fastapi import File, UploadFile from typing import List @app.post("/upload") def upload(files: List[UploadFile] = File(...)): for file in files: try: contents = file.file.read() # store contents to the database except Exception: return {"message": "Error uploading file(s)"} finally: file.file.close() return {"message": f"Successfully uploaded {[file.filename for file in files]}"}
来自 Python 脚本的请求:
requests.post(url="SERVER_URL/create_file", files={"file": (f.name, f, "multipart/form-data")})
以上是如何解决FastAPI上传空文件问题?的详细内容。更多信息请关注PHP中文网其他相关文章!