FastAPI allows you to upload multiple files in at the same time.
Example 1: Using List[bytes]
@app.post("/files/")
async def create_file(files: List[bytes] = File(...)):
    contentReceived = []
    for file in files:
        contentReceived.append(str(file))
    return {"contentReceived": contentReceived}
Example 2: Using List[UploadFile]
@app.post("/uploadfiles/")
async def create_upload_file(files:List[UploadFile] = File(...)):
    fileNames = []
    for file in files:
        fileNames.append(file.filename)
    return {"fileNames": fileNames}
Find the below working application.
multipleFileuploads.py
from fastapi import FastAPI, File, UploadFile
from typing import List
app = FastAPI()
@app.post("/files/")
async def create_file(files: List[bytes] = File(...)):
    contentReceived = []
    for file in files:
        contentReceived.append(str(file))
    return {"contentReceived": contentReceived}
@app.post("/uploadfiles/")
async def create_upload_file(files:List[UploadFile] = File(...)):
    fileNames = []
    for file in files:
        fileNames.append(file.filename)
    return {"fileNames": fileNames}
Open terminal and execute the command ‘uvicorn multipleFileuploads:app --reload’.
$uvicorn multipleFileuploads:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28879] using statreload
INFO:     Started server process [28881]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
Open the url ‘http://localhost:8000/docs’ in browser and experiment with swagger documentation.
Previous Next Home
No comments:
Post a Comment