【发布时间】: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 作为单个参数发送,与其他参数组合发送。 (嗯,你可以,但这对接收者没有意义。)你需要将
type和user_id附加到 FormData 对象,就像你对文件所做的那样,然后发送 only 普通的 FormData 对象。 -
@CBroe 我已经将
type和user_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