Cannot upload multiple images from form with FastAPI

Overview

This is a reminder when I tried to upload multiple images to fastapi's backend server from the normal html <input type =" file "...> tag instead of using js.

Problem code

index.html


 <html>
        <head>
            <title>Face Swap App</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
            <form enctype="multipart/form-data" method="post" action="swap">
                <input type="file" id="source" name="file"></input>
                <input type="file" id="target" name="file"></input>
                <input type="submit" value="Face Swap">
            </form>
        </body>
    </html>

main.py



@app.post("/swap", response_class=HTMLResponse)
async def create_swapped_image(files: List[UploadFile] = File(...)):
    print(files)
    return """
    <html>
        <head>
            <title>Face Swap App</title>
        </head>
        <body>
            <h1>Success!</h1>
        </body>
    </html>
    """

Solution

In conclusion, it seems that the name of the input tag needs to be the same as the argument of the function of the fastapi endpoint! In other words, the input of index.html

index.html



<input type="file" id="source" name="files">
<input type="file" id="target" name="files">

It was solved by changing to. I haven't read all of them, but I don't remember writing this in the official doc, so I thought it would be difficult to understand. I'm sorry if I wrote it ...

Recommended Posts

Cannot upload multiple images from form with FastAPI
Post multiple Twitter images with python
Animate multiple still images with Python
Upload and download images with falcon
Convert PIL format images read from form with Django to base64 format
Upload images to Google Drive with Python
Save multiple models in one form with Django
I want to display multiple images with matplotlib.
Bulk download images from specific URLs with python
Upload images to S3 with GUI using tkinter
[Memo] Subscribe messages from multiple topics with ROS
Convert images from FlyCapture SDK to a form that can be used with openCV
Images created with matplotlib shift from dvi to pdf
Bulk download images from specific site URLs with python
Face detection from images taken with Raspberry Pi camera
Remove headings from multiple format CSV files with python