1

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?

1 Answer 1

0

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.