How to Upload Files using FastAPI

In this tutorial, we will learn how to upload both single and multiple files using FastAPI.

To receive uploaded files using FastAPI, we must first install python-multipart using the following command:


pip3 install python-multipart

In the given examples, we will save the uploaded files to a local directory asynchronously. To achieve this, let us use we will use aiofiles library.

The following commmand installs aiofiles library:


pip3 install aiofiles

Uploading Single File


from fastapi import FastAPI, File, UploadFile
import uvicorn
import aiofiles

app = FastAPI()

@app.post("/upload-file")
async def create_upload_file(file: UploadFile = File(...)):
    print("filename = ", file.filename) # getting filename
    destination_file_path = "/home/abc/videos/"+file.filename # location to store file
    async with aiofiles.open(destination_file_path, 'wb') as out_file:
        while content := await file.read(1024):  # async read file chunk
            await out_file.write(content)  # async write file chunk

    return {"Result": "OK"}
    
if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8005)
    print("running")

Uploading Multiple Files


from fastapi import FastAPI, File, UploadFile
import uvicorn
import aiofiles
from typing import List

app = FastAPI()

@app.post("/upload-files")
async def create_upload_files(files: List[UploadFile] = File(...)):
    for file in files:
        destination_file_path = "/home/fm-pc-lt-46/Music/"+file.filename #output file path
        async with aiofiles.open(destination_file_path, 'wb') as out_file:
            while content := await file.read(1024):  # async read file chunk
                await out_file.write(content)  # async write file chunk    
    return {"Result": "OK", "filenames": [file.filename for file in files]}
    
if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8005)
    print("running")