我正在做一个上传头像功能,前端使用vue.js,后端是springboot构建的项目,但是每次vue请求传到后端时,都会报格式错误。代码如下:
后端接口:
@PostMapping("/userinfo/uploadHeadImg")
public AjaxResult<?> uploadHeadImg(@RequestParam MultipartFile file, @RequestParam Integer userInfoId) throws Exception{
return tbUserinfoService.uploadHeadImg(file,userInfoId);
}
html部分:
<div class="setting-head">
<!--个人头像-->
<div class="user-head-img" >
<div class="use-click" @click="uploadHeadImg">
<el-avatar :size="60" :src="userHeadImg" >
</el-avatar>
<input type="file" accept="image/*" class="hiddenInput" @change="handleFile"/>
</div>
</div>
</div>
js部分:
handleFile: function (e) {
let $target = e.target || e.srcElement;
let file = $target.files[0];
var reader = new FileReader();
reader.onload = (data) => {
let res = data.target || data.srcElement;
this.$store.dispatch("uploadHeadImg",file);
};
reader.readAsDataURL(file)
},
store.js 文件部分:
actions:{
uploadHeadImg({commit,state},file){
Vue.http.post('/userinfo/uploadHeadImg',{file:file,userInfoId:state.userInfoId},
{headers: { 'Content-Type': 'multipart/form-data' }},
).then(function(res){
var result = res.data;
if(result.code=="200"){
this.userHeadImg = res.result;
commit("setUserHeadImgFile",file);
}
})
}
报错现象分两种情况:
当store.js部分添加了
{headers: { 'Content-Type': 'multipart/form-data' }},
后,后端报错如下:
Resolved [org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found]
我在网上找了大部分的解决方式是说去掉 header请求中的 Content-Type就行了。
但是当我去掉这部分后报错又变成了:
Resolved [org.springframework.web.multipart.MultipartException: Current request is not a multipart request]
网上搜索解决方式:说请求头添加
'Content-Type': 'multipart/form-data'
陷入死循环中....
希望有熟悉这部分的老哥可以帮忙请求看看,谢谢!!!
通过postman测试,后端接口成功,但就是通过vue访问就会报错