Home >Backend Development >Python Tutorial >How to Efficiently Upload Files to a FastAPI Server Using `form-data`?
Uploading Files with FastAPI Using form-data and SpooledTemporaryFile
To upload files using FastAPI with multipart/form-data, it's recommended to install python-multipart as multipart files are sent via form-data.
pip install python-multipart
Here's an improved example of uploading a file using FastAPI:
from fastapi import File, UploadFile from typing import List @app.post("/upload") def upload(file: UploadFile = File(...)): try: # Using file.file for synchronous operations (e.g., opening a file on disk) contents = file.file.read() with open(file.filename, 'wb') as f: f.write(contents) except Exception: return {"message": "An error occurred while uploading the file."} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}"}
If you need to process larger files in chunks, consider reading the file in smaller increments. You can either use a manual loop:
@app.post("/upload") def upload(file: UploadFile = File(...)): try: with open(file.filename, 'wb') as f: while contents := file.file.read(1024 * 1024): f.write(contents) except Exception: return {"message": "An error occurred while uploading the file."} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}"}
Or, use the shutil.copyfileobj() method, which reads and writes data in chunks:
from shutil import copyfileobj @app.post("/upload") def upload(file: UploadFile = File(...)): try: with open(file.filename, 'wb') as f: copyfileobj(file.file, f) except Exception: return {"message": "An error occurred while uploading the file."} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}"}
Additional Notes:
The above is the detailed content of How to Efficiently Upload Files to a FastAPI Server Using `form-data`?. For more information, please follow other related articles on the PHP Chinese website!