如何使用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中文網其他相關文章!