javascript - 如何使用 JavaScript 和 FastAPI 上传多个文件?
问题描述
我关注了 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'
}
})
}
动作.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)
我该如何解决这个问题以及如何使用我在上传端点中收到的那些文件?
解决方案
我最近遇到了同样的问题,无法用 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])
}
推荐阅读
- python - PyTorch:是否有类似于 Keras 的 fit() 的明确训练循环?
- android - 为什么android Room需要互联网连接来存储数据
- powershell - 如何使用 Poweshell 脚本将 IIS 站点详细信息从多个服务器导出到 excel 表
- clojure - 可以更好地避免 nil conjoins 吗?
- c# - DevOps 构建正在为不再存在的项目加载旧的 .dll 文件
- design-patterns - 如果 Model 被替换,是否有任何重新订阅的设计模式?
- vba - 使用 Word VBA 更新 Excel 链接图表源
- javascript - 无法解决反应导航
- c++ - 如何在派生类中使用来自基本模板化接口的朋友 cin/cout 函数
- error-handling - 你能返回一个适用于任何可能错误类型的结果吗?