如何使用Fastapi和Vue上传文件?我收到了无法处理的错误422 [英] How to upload file using fastapi with vue? I got error unprocessable 422
问题描述
我尝试将文件上传到目录中,我在Python中使用vue.js和fastapi.
I am try to upload a file into a directory, I am using vue.js and fastapi in Python.
但是每次我遇到错误422无法处理的函数时.
But every time I get an error 422 unprocessable function.
我试图这样使用官方文档:
I tried to use the official doc like this:
<!-- Vue Template -->
<input
style="display: none"
type="file"
name="files"
ref="fileAdd"
v-on:change="handleFilesChange()"
/>
// Vue Script
handleFilesChange() {
var uploadedFiles = this.$refs.fileAdd.files;
if (uploadedFiles.length > 0) {
for (var i = 0; i < uploadedFiles.length; i++) {
this.files.push(uploadedFiles[i]);
var formData = new FormData();
formData.append("files", this.$refs.fileAdd.files[0]);
axios
.post(url + "/uploadfile", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
onUploadProgress: (uploadStatus) => {
this.uploadProgress = Math.round(
(uploadStatus.loaded / uploadStatus.total) * 100
);
this.isUplading = true;
},
})
.then((response) => {do something}
}
}
}
# FastAPI endpoint
@app.post('/uploadfile')
async def upload_file(sid: str, files: List[UploadFile]=File(...)):
print(files)
if(files == []):
print("No Files")
else:
print(files[0].filename)
#...do something
我收到错误422无法处理.
and I got error 422 unprocessable.
有什么办法解决这个问题吗?
Any idea how to solve this problem?
推荐答案
我不是vuejs专家(也不是javascript),但我认为问题在于您要传递给axios:
I'm not a vuejs expert (nor javascript), but I think the problem is what you are passing to axios:
formData.append("files",this.$ refs.fileAdd.files [0]);
在上面一行中,您(据我所了解的vuejs和您的代码)是单个文件( [0]
),而不是文件数组.
with the above line, you are (as far as I've understood vuejs and your code), a single file (the [0]
) instead of an array of files.
想法是传递文件数组,我认为可以通过以下方式实现:
The idea is to pass an array of files, which I guess could be achieved as follows:
formData.append("files",this.$ refs.fileAdd.files);
或
formData.append("files",[this.$ refs.fileAdd.files [0]]);
已经提出并回答了类似的问题,因此值得一看如何使用JavaScript上传多个文件和FastAPI?
A similar question has been already asked and answered, so it may be worth giving it a look How can I upload multiple files using JavaScript and FastAPI?
这篇关于如何使用Fastapi和Vue上传文件?我收到了无法处理的错误422的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!