Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 609
John Doe Avatar asked May 09 '26 17:05

John Doe


1 Answers

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])
}
like image 116
Jan-Timo Hesse Avatar answered May 11 '26 07:05

Jan-Timo Hesse