0
0
FastAPIframework~5 mins

File upload (single file) in FastAPI

Choose your learning style9 modes available
Introduction

Uploading files lets users send documents or images to your app. It helps your app receive data like photos or reports.

When users need to upload a profile picture.
When a form requires a document like a resume or certificate.
When users want to send a single image for processing.
When collecting one file for storage or review.
When your app needs to accept one file at a time from users.
Syntax
FastAPI
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    return {"filename": file.filename, "content_type": file.content_type}

UploadFile is used to handle the uploaded file efficiently.

File(...) marks the parameter as required for upload.

Examples
This example returns only the uploaded file's name.
FastAPI
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}
This example reads the file content and returns its size in bytes.
FastAPI
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    size = len(contents)
    return {"filename": file.filename, "size_bytes": size}
Sample Program

This complete FastAPI app accepts one uploaded file. It reads the file content to get its size and returns the file name, type, and size as JSON.

FastAPI
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    return {
        "filename": file.filename,
        "content_type": file.content_type,
        "size_bytes": len(contents)
    }
OutputSuccess
Important Notes

Use UploadFile for better performance with large files instead of reading all bytes at once.

Always check file.content_type to validate file types for security.

Remember to handle exceptions for missing or invalid files.

Summary

Use UploadFile and File(...) to accept single file uploads in FastAPI.

Read file content asynchronously with await file.read() to get file data.

Return useful info like filename, content type, and size to confirm upload success.