【问题标题】:how to send files using formData() in an api request using vuejs and axios如何使用 vuejs 和 axios 在 api 请求中使用 formData() 发送文件
【发布时间】:2021-12-08 12:37:58
【问题描述】:

我想通过 API 将文件上传到服务器。在documenter.getpostman上,这是API的使用方法

--form 'type="1"' \
--form 'user_id="1"' \
--form 'file=@"/C:/Users/xxx/Downloads/xxx.postman_collection.json"' 

这就是我所做的


                try {
                    const fd = new FormData()
                    fd.append('file', this.dropFiles)
                
                    let response = await this.$axios.post('/staff/customer/add/document', {
                        type: this.uploadType,
                        user_id: this.user_id,
                        file: fd,
                    })

                    console.log(response.data.success)    
                }
                catch(err){
                     console.log(err)
                }

this.dropFiles 包含来自input type="file" 的文件,当我将其记录到控制台时,我能够看到它的内容,但是记录带有表单数据的fd 总是返回一个空对象。 type: this.uploadType, user_id: this.user_id 是我发送到 api 的其他参数

请求总是返回 400(错误请求)

Error: Request failed with status code 400
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.onloadend (xhr.js?b50d:54)

我不确定 API 是否需要文件的路径,因为,我已经尝试将文件路径硬编码到这样的请求中

let response = await this.$axios.post('/staff/customer/add/document', {
    type: this.uploadType,
    user_id: this.user_id,
    file: '/home/myDevice/Downloads/download.jpeg',
})

但仍然得到相同的响应。我需要我能得到的所有帮助,谢谢。

【问题讨论】:

  • 您不能将 FormData 作为单个参数发送,与其他参数组合发送。 (嗯,你可以,但这对接收者没有意义。)你需要将 typeuser_id 附加到 FormData 对象,就像你对文件所做的那样,然后发送 only 普通的 FormData 对象。
  • @CBroe 我已经将typeuser_id 都附加到了formData 就像你说的那样,我仍然遇到同样的错误,当我使用开发工具网络检查有效负载时请求中,file 是一个空对象。
  • 您是否也修改了作为第二个参数传递给post 方法的内容?
  • @CBroe 这是我在将两者都附加到fd ``` let response = await this.$axios.post('/staff/customer/add/document', { file : fd }) ``
  • 您只需要发送 formdata 对象。现在,您仍在尝试发送一个对象,该对象包含属性名称 file 下的 formdata 对象。 { file: fd }-> fd

标签: javascript vue.js axios form-data


【解决方案1】:

使用@CBroe 评论解决了这个问题。 我将typeuser_id 都附加到formData 中,然后传入formData 对象。

                try {
                    const fd = new FormData()
                    fd.append('file', this.dropFiles)
                    fd.append('type', this.uploadType)
                    fd.append('name', this.fileName)
                    fd.append('user_id', this.user_id)
                
                    let response = await this.$axios.post('/staff/customer/add/document', fd)

                    console.log(response.data.success)    
                }
                catch(err){
                     console.log(err)
                }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2021-10-22
    • 2019-01-04
    • 2021-10-27
    • 2020-05-12
    • 1970-01-01
    • 2019-10-29
    • 2021-10-30
    相关资源
    最近更新 更多