How to Upload Files using FastAPI

In FastAPI, you can easily handle file uploads using the File data type from the fastapi module. You'll also need to use a library like python-multipart for parsing multipart/form-data requests.

Follow these steps to upload files in FastAPI:

  1. Install fastapi:
  2. pip install fastapi
    
  3. Install python-multipart:
  4. pip install python-multipart
    
  5. Install aiofiles:
  6. pip install aiofiles
    

    The aiofiles library helps to upload files asynchronously.

  7. Create and endpoint to handle file uploads:
  8. from fastapi import FastAPI, File, UploadFile
    import uvicorn
    import aiofiles
    from typing import List
    
    app = FastAPI()
    
    @app.post("/single-file")
    async def upload_single_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"}
    
    
    @app.post("/multiple-files")
    async def upload_multiple_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")
    

    In this code example, we define two endpoints: /single-upload/, which accepts a POST request with an UploadFile parameter, and /multiple-uploads/, which accepts a POST request with a list of UploadFile parameter. The uploaded files are then processed and saved to the server with their original filenames.

  9. Run Application:
  10. python main.py