How can I upload multiple files using JavaScript and FastAPI?

两盒软妹~` 提交于 2021-02-11 14:37:56

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/65510798/how-can-i-upload-multiple-files-using-javascript-and-fastapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!