File uploads are a common feature in many web applications. In FastAPI, handling file uploads is straightforward and can be achieved using the UploadFile
type. This guide will demonstrate how to create a file upload endpoint in FastAPI.
Creating the Endpoint
Python
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
with open(f"uploads/{file.filename}", "wb") as f:
f.write(file.file.read())
return {"message": "File uploaded successfully"}
Explanation
- The
UploadFile
type is used to represent the uploaded file. - The
File(...)
parameter indicates that thefile
argument is required. - The
with
statement ensures that the file is closed properly after it’s written to the disk.
Storing Uploaded Files
You can store uploaded files in a specific directory or upload them to a cloud storage service like Amazon S3, Google Cloud Storage, or Backblaze B2.
Example: Storing Files Locally
Python
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
upload_folder = "uploads"
file_path = os.path.join(upload_folder, file.filename)
with open(file_path, "wb") as f:
f.write(file.file.read())
return {"message": "File uploaded successfully", "file_path": file_path}
By following these steps, you can effectively implement file upload functionality in your FastAPI application, allowing users to upload files to your server.