Home >Backend Development >Python Tutorial >How to Solve Empty File Upload Issues in FastAPI?
How to Upload File using FastAPI?
Problem:
When using FastAPI to upload a file according to the official documentation, the file2store variable remains empty.
Cause:
Solution:
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}"}
Alternative for Async Endpoints:
@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}"}
Uploading Multiple Files:
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]}"}
Request from Python Script:
requests.post(url="SERVER_URL/create_file", files={"file": (f.name, f, "multipart/form-data")})
The above is the detailed content of How to Solve Empty File Upload Issues in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!