```java
@ResponseBody
@RequestMapping(value = "/updateSingerPic", method = RequestMethod.POST)
public Object updateSingerPic(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id")int id){
JSONObject jsonObject = new JSONObject();
if (avatorFile.isEmpty()) {
jsonObject.put(Consts.CODE, 0);
jsonObject.put(Consts.MSG, "文件上传失败!");
return jsonObject;
}
//文件名=当前时间到毫秒+原来的文件名
String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
//文件路径
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator") + "singerPic" ;
//如果文件路径不存在,新增该路径
File file1 = new File(filePath);
if (!file1.exists()){
file1.mkdir();
}
//实际的文件路径
File dest = new File(filePath + System.getProperty("file.separator") + fileName);
//存储到数据库里的相对文件地址
String storeavatorPath = "/img/singerPic/"+fileName;
try {
avatorFile.transferTo(dest);
Singer singer = new Singer();
singer.setId(id);
singer.setPic(storeavatorPath);
boolean flag = singerService.update(singer);
if (flag){
jsonObject.put(Consts.CODE, 1);
jsonObject.put(Consts.MSG, "上传成功");
jsonObject.put("pic",storeavatorPath);
return jsonObject;
}
jsonObject.put(Consts.CODE, 0);
jsonObject.put(Consts.MSG, "上传失败");
return jsonObject;
}catch (IOException e){
jsonObject.put(Consts.CODE, 0);
jsonObject.put(Consts.MSG, "上传失败"+e.getMessage());
}finally {
return jsonObject;
}
}
这是我写的后端上传头像代码
```Vue
<template slot-scope="scope">
<div class="singer-img">
<img :src="getUrl(scope.row.pic)" alt="" style="width: 100%;"/>
</div>
<el-upload :action="uploadUrl(scope.row.id)" :before-upload="beforeAvatarUpload"
:on-success="handleAvatarSuccess">
<el-button size="mini">更新图片</el-button>
</el-upload>
</template>
</script>
import { mixin } from '../mixins/index';
uploadUrl(id){
return `${this.$store.state.HOST}/singer/updateSingerPic?id=${id}`
}
</script>
mixins里面的index.js
handleAvatarSuccess (res) {
let _this = this;
if (res.code == 1) {
_this.getData();
_this.notify({
title: '上传成功',
type: 'success'
})
} else {
console.log(res); // 打印整个res对象
_this.notify({
title: '上传失败',
type: 'error'
})
}
},
//上传图片之前的检查
beforeAvatarUpload (file) {
const isJPG = (file.type == 'image/jpeg') || (file.type == 'image/png')
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
return false;
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
return false;
}
return true;
}
这是前端头像上传的代码
在网页中上传头像提示{ "title": "上传失败", "type": "error" },但是成功在文件夹中创建了头像文件,请问该问题要怎么解决