Uploading Multiple Files in FastAPI

When you create an html form which can take multiple file inputs in that case all the files will be send to the server and the “/upload” endpoint will no longer be valid because the decorator function for that endpoint only takes single UploadFile, for the above endpoint to work with multiple files we need to pass list[UploadFile] as an argument to the “/upload” endpoint decorator function. So all the files uploaded to the /upload endpoint will be stored in the list.

Change the Above HTML code to take multiple file inputs:

HTML




<!DOCTYPE html>
<html>
<head>
    <title>GFG</title>
</head>
<body>
    <h2>Geeks for Geeks </h2>
    <form action="http://127.0.0.1:8000/upload" method="POST" enctype="multipart/form-data">
        <!-- File input field -->
        <label for="file">Choosen file will be saved on server :</label>
        <input type="file" name="files" accept=".jpg" multiple>
     
        <br><br>
         
        <!-- Submit button -->
        <input type="submit" value="Upload">
    </form>
</body>
</html>


app.py: In the above code we specified the data type in the uploadfile function to be a list[UploadFile]. Then we loop through each of the file submitted by the user and saved it on the server.

Python3




from fastapi import FastAPI, UploadFile
app = FastAPI()
@app.post("/upload/")
async def uploadfile(files: list[UploadFile]):
    try:
        for file in files:
            file_path = f"C:\\Users\\hp\\OneDrive\\Documents\\gfg/{file.filename}"
                        with open(file_path, "wb") as f:
                f.write(file.file.read())
                return {"message": "File saved successfully"}
    except Exception as e:
        return {"message": e.args}


Output:

Now to be able to access the /upload endpoint we need to use uvicorn. Copy paste the below commmand in the terminal :

python -m uvicorn app::app –reload

Form.html

In the above image. You have to Choose the Files and then Click on the Upload Button. It Directly Redirect to the /Upload Url and return a dictionary with {“message”:”File saved successfully”}. After that You can check. the file has successfully saved on your localhost server.



Save UploadFile in FastAPI

FastAPI is an easy, fast, and robust web framework for creating API’s with Python 3.7+. It was created by Sebastian Ramirez. It is built on top of Starlette and Pydantic, both of which are asynchronous libraries i.e. they use async and await to serve the requests efficiently. FastAPI makes routing, session management, authentication, and file uploads very easy.

Similar Reads

What is UploadFile in FastAPI?

UploadFile is a class provided by the FastAPI for handling files. You can define UploadFile as an argument to a function for an HTTP endpoint. So when a user sends an HTTP request containing a file, all information regarding that file will be passed to the function using the UploadFile instance. UploadFile class has the following attributes for getting information about the file submitted by the user:...

Uploading Single Files in FastAPI

form.html: Below is a simple HTML code snippet for taking a file as input and submit it to the localhost /upload endpoint. Create a folder named gfg and create a file named form.html in it. Copy the below code and paste it in the form.html file...

Uploading Multiple Files in FastAPI

...