To check the size of an uploaded file in FastAPI and ensure it does not exceed 500MB, you can use the UploadFile class and inspect its content_length property. Below is an example code that checks the file size and raises an exception if it exceeds the specified limit.
from fastapi import FastAPI, UploadFile, HTTPException
app = FastAPI()
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
# Maximum allowed file size (500MB)
max_file_size = 500 * 1024 * 1024 # 500MB
# Check the file size
if file.content_length > max_file_size:
raise HTTPException(status_code=413, detail="File size exceeds the limit of 500MB")
# Additional logic to handle or store the file can be added here.
# For example, use file.filename to get the file name and file.file to process the file content.
return {"filename": file.filename}
In this code, file.content_length represents the size of the uploaded file. If this value is greater than max_file_size, an HTTPException is raised, and the client receives a response with the message "File size exceeds the limit of 500MB."
By limiting the file size in this way, the server can respond appropriately when a client attempts to upload a file that exceeds the defined limit.