前端代码
前端 style 样式
<style>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
前端图片的组件
<el-form-item label="商品封面">
<el-upload v-model="formData.shopImage"
action="/shop/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
前端 axios 请求
//图片上传成功后的回调方法 返回图片名称
handleAvatarSuccess(res ,file){
console.log(res)
this.imageUrl ="/shop/download?filename="+res;
this.formData.shopImage=res;
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
后端代码
//下载图片
@RequestMapping("/download")
public void download(String filename, HttpServletResponse response) {
FileInputStream fs=null;
ServletOutputStream fos=null;
try {
fs=new FileInputStream("C:\\Users\\17630\\Pictures\\Saved Pictures\\"+filename);
fos=response.getOutputStream();
byte[] arr=new byte[1024];
int length= -1;
while ((length=fs.read(arr))!=-1){
fos.write(arr,0,length);
fos.flush();
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fs.close();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//上传图片
@RequestMapping("/upload")
public String upload(MultipartFile file){
String filename = file.getOriginalFilename();
String fileType = filename.substring(filename.lastIndexOf("."));
filename= UUID.randomUUID().toString().replace("-","")+fileType;
// File picFile = new File("C://Users//17630//Pictures//Saved Pictures//"+filename);
File picFile = new File("C:\\Users\\17630\\Pictures\\Saved Pictures\\"+filename);
try {
file.transferTo(picFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
return filename;
}