Question
I am try to upload a file into a directory, I am using vue.js and fastapi in Python.
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
and I got error 422 unprocessable.
Any idea how to solve this problem?
Answer
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]);
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);
or
formData.append("files", [this.$refs.fileAdd.files[0]]);
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?](https://stackoverflow.com/questions/65510798/how-can-i-upload- multiple-files-using-javascript-and-fastapi/65513660#65513660)