Bagaimana hendak Muat Naik Fail menggunakan FastAPI?
Masalah:
Apabila menggunakan FastAPI untuk memuat naik fail mengikut kepada dokumentasi rasmi, pembolehubah file2store kekal kosong.
Punca:
Penyelesaian:
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}"}
Alternatif untuk Async Titik tamat:
@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}"}
Memuat naik Berbilang Fail:
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]}"}
Permintaan daripada Skrip Python:
requests.post(url="SERVER_URL/create_file", files={"file": (f.name, f, "multipart/form-data")})
Atas ialah kandungan terperinci Bagaimana untuk Menyelesaikan Isu Muat Naik Fail Kosong dalam FastAPI?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!