【实习小tip】axios发送POST请求时携带文件加参数的写法以及文件上传报错:Current request is not a multipart request
axios发送POST请求时携带文件加参数的写法以及文件上传报错:Current request is not a multipart request
·
问题:axios发送POST请求时携带文件加参数的写法以及文件上传报错:Current request is not a multipart request
Current request is not a multipart request说明你的请求跟普通请求不一样,这里是携带了文件并且有参数,就需要携带FormData格式的参数,不然会导致传过去的文件参数为空
数据格式采用 FormData,并用自带的append参数将属性键值对全都放进formdata
const formdata=new FormData()
formdata.append("attribute",this.attribute)
formdata.append("file",this.uploaderFileObj)
formdata.append("proportionOfWeight",this.proportionOfWeight)
formdata.append("remark",this.remark)
formdata.append("templateName",this.templateName)
formdata.append("type",this.type)
除此之外还要设置请求头里的Content-Type
multipart/form-data(指定传输数据为二进制类型
,比如图片、mp3、文件)
同时还需要规定一个内容分割符boundary用于分割请求体中不同参数的内容(普通post请求的参数分割符默认为&,参数与参数值的分隔符为=)
axios({
url: `${process.env.REQUEST_BASE_URL}${process.env.BASE_API}/v1/appraisal/template/excel`,
method: 'post',
headers: {
'Content-Type':'multipart/form-data; boundary=----WebKitFormBoundaryVCFSAonTuDbVCoAN',
Authorization: 'Bearer ' + Cookies.get(process.env.TOKEN_KEY),
},
data:formdata,
})
完整代码:
// 上传
uploadUserList(item) {
const fileObj = item.file
console.log(item.file)
this.uploaderFileObj = fileObj
this.disabledImport = false
this.stepActive = 1
},
// 确认上传导入
confirmImportUser() {
if (!this.uploaderFileObj) {
return
}
const formdata=new FormData()
formdata.append("attribute",this.attribute)
formdata.append("file",this.uploaderFileObj)
formdata.append("proportionOfWeight",this.proportionOfWeight)
formdata.append("remark",this.remark)
formdata.append("templateName",this.templateName)
formdata.append("type",this.type)
axios({
url: `${process.env.REQUEST_BASE_URL}${process.env.BASE_API}/v1/appraisal/template/excel`,
method: 'post',
headers: {
'Content-Type':'multipart/form-data; boundary=----WebKitFormBoundaryVCFSAonTuDbVCoAN',
Authorization: 'Bearer ' + Cookies.get(process.env.TOKEN_KEY),
},
data:formdata,
})
.then(({
data
}) => {
if (data && data.code == 200) {
this.$message({
message: '导入成功',
type: 'success',
duration: 1500,
})
this.stepActive = 3
this.waitImport = false
this.finishImport()
} else {
this.$message({
message: '导入失败!' + data.msg,
type: 'warning',
duration: 2500,
onClose: () => {},
})
}
})
.catch(() => {
this.$message.error('异常错误')
})
},
POST请求和GET请求载荷在浏览器控制台查看的区别
POST请求的载荷params:
GET请求的载荷data:
特殊情况:POST请求传multipart/form-data形式的data参数(文件加参数)
更多推荐
已为社区贡献4条内容
所有评论(0)