LoginSignup
0
1

More than 3 years have passed since last update.

FastAPIでformから複数画像をアップロードできない

Posted at

概要

jsを使ってではなく、普通のhtmlの<input type="file" ...>タグからfastapiのバックエンドサーバーに複数画像をアップロードしようとした時にはまった備忘録です。

問題コード

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>
    """

解決法

結論から言えばinputタグのnameをfastapiのエンドポイントの関数の引数と同じにする必要があるようです!つまりindex.htmlのinputを

index.html

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

に変えることで解決しました。
全部読んだわけではないですが、こんなこと公式docに書いていた記憶がないのでわかりづらいなあと思いました。書いていたらごめんなさい、、

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1