【问题标题】:How can I upload multiple files using JavaScript and FastAPI?如何使用 JavaScript 和 FastAPI 上传多个文件?
【发布时间】:2020-12-30 17:06:18
【问题描述】:

我关注了 FastAPI 文档,并尝试将文件从我的客户端以 js 编写发送到我的服务器,该服务器以 FastAPI 编写。

我的 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>    

我的上传文件.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')

    

并且无法成功获取文件,我在服务器端收到错误:

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

客户:

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)

我该如何解决这个问题以及如何使用我在上传端点中收到的那些文件?

【问题讨论】:

    标签: javascript fastapi


    【解决方案1】:

    我最近遇到了同样的问题,无法用 Isabi 提到的答案来解决。但它给了我正确的想法:

    文件可以彼此分开添加,重要的是两者都使用相同的名称作为参数:

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

    或者如果你已经在使用文件数组:

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

    【讨论】:

      【解决方案2】:

      问题可能是由于您传递了参数file1file2 而端点需要List 的名为files 的文件。

      我还没有测试过代码,但基本的想法是用实际文件创建一个数组并将其添加到FormData 名称files 下。下面的代码应该可以让您了解如何实现目标。

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

      或者,如果我的解决方案不起作用,您可以尝试使用这个Uploading multiple files using formData(),但同样,我的回答主要是引导您走向正确的道路。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-12
        • 1970-01-01
        • 2021-04-19
        • 2021-08-16
        • 1970-01-01
        • 1970-01-01
        • 2016-12-13
        相关资源
        最近更新 更多