【问题标题】:How to upload file using fastapi with vue? I got error unprocessable 422如何使用 fastapi 和 vue 上传文件?我收到错误无法处理 422
【发布时间】:2021-01-22 13:32:28
【问题描述】:

我正在尝试将文件上传到目录中,我在 Python 中使用 vue.js 和 fastapi。

但是每次我得到一个错误 422 无法处理的函数。

我尝试这样使用官方文档:

<!-- 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 无法处理。

知道如何解决这个问题吗?

【问题讨论】:

    标签: python python-3.x vue.js vuejs2 fastapi


    【解决方案1】:

    我不是 vuejs 专家(也不是 javascript),但我认为问题在于您传递给 axios 的内容:

    formData.append("files", this.$refs.fileAdd.files[0]);

    通过上面的行,您(就我对 vuejs 和您的代码的理解而言)是一个文件([0]),而不是一个文件数组。

    思路是传递一个文件数组,我猜可以这样实现:

    formData.append("files", this.$refs.fileAdd.files);

    formData.append("files", [this.$refs.fileAdd.files[0]]);

    已经提出并回答了一个类似的问题,因此可能值得一看 How can I upload multiple files using JavaScript and FastAPI?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多