John Doe
John Doe

Reputation: 423

How can I upload multiple files using JavaScript and FastAPI?

I followed FastAPI docs and I am trying to send files from my client that wrote in js to my server that wrote in FastAPI.

My HTML:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-2.0.3.js" integrity="sha256-lCf+LfUffUxr81+W0ZFpcU0LQyuZ3Bj0F2DQNCxTgSI=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    </head>

    <body>
            <input id='fileid' type='file' value="Load miRNA data"/>
            <input id='fileid2' type='file' value="Load Target data"/>
            <input id='buttonid' type='button' value='Upload' />
    </body>
    <script type="text/javascript" src="./uplaodfiles.js"></script>
 </html>    

my uploadfiles.js

document.getElementById('buttonid').addEventListener('click', generate);

function generate() {
  let file = document.getElementById("fileid").files[0];
  let file2 = document.getElementById("fileid2").files[0];
  let formData = new FormData();
  formData.append("file",file,file.name)
  formData.append("file2",file2,file2.name)
  console.log(formData)
  axios.post('http://127.0.0.1:8000/actions/upload', formData, {
    headers: {
      'content-Type': 'multipart/form-data'
    }
})
}

action.py

from typing import List
from fastapi import APIRouter,Header,HTTPException,FastAPI, File, UploadFile

router = APIRouter()

import pandas as pd

@router.post('/upload')
def upload_file(files: List[UploadFile] = File(...)):
        print('Arrived')

    

and cant succesfully get the files and I get the error in my server side:

INFO:     127.0.0.1:59210 - "POST /actions/upload HTTP/1.1" 422 Unprocessable Entity

client:

Uncaught (in promise) Error: Request failed with status code 422
    at e.exports (isAxiosError.js:10)
    at e.exports (isAxiosError.js:10)
    at XMLHttpRequest.l.onreadystatechange (isAxiosError.js:10)

How can I solve this and how can I use those files that I recieve in my upload endpoint?

Upvotes: 3

Views: 4378

Answers (2)

Jan-Timo Hesse
Jan-Timo Hesse

Reputation: 73

I recently faced the same problem and could not solve it with the answer Isabi mentioned. But it gave me the right idea:

The files can be appanded separately from each other, important is that both uses the same name as argument:

formData.append('files',file)
formData.append('files',file2)

Or if you already using a file array:

let formData = new FormData();
for (var i = 0; i < files.length; i++){
    formData.append('files',files[i])
}

Upvotes: 3

lsabi
lsabi

Reputation: 4476

The problem is likely due to the fact that you pass the parameters file1 and file2 when the endpoint expects a List of files named files.

I haven't tested the code, but the basic idea so to create an array with the actual files and add it to the FormData under the name files. Below the code that should give you the idea of how to achieve your goal.

let formData = new FormData();
formData.append("files",[file, file2]);

Alternatively, if my solution does not work, you can try with this one Uploading multiple files using formData(), but again, my answer is mainly to guide you to the right path.

Upvotes: 0

Related Questions