数据模型:
imageUrl: '',
<el-form-item label="楼盘图片:" prop="pic" class="uploadImg" v-model="emp.pic">
<el-upload
class="avatar-uploader"
action="/premises/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>
/*图片上传下载*/
handleAvatarSuccess(res, file) {
this.imageUrl = "/premises/download?filename="+res;
this.emp.pic=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;
},
图片上传
/**
* 图片上传
* @return
*/
@PostMapping("upload")
public String Upload(MultipartFile file){
//获取文件名称,使用UUID工具类为文件重命名
String filename = file.getOriginalFilename();
System.out.println(filename);
File fileDir = new File("D://imgs//"+filename);
try {
file.transferTo(fileDir);
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
图片下载
@GetMapping("/download")
public void download(String filename, HttpServletResponse response){
FileInputStream fileInputStream=null;
ServletOutputStream outputStream=null;
try {
fileInputStream=new FileInputStream(new File("D://imgs/"+filename));
outputStream= response.getOutputStream();
int len=0;
byte[] bytes=new byte[1024];
while ((len=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes);
outputStream.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
表格
<template slot-scope="scope">
<img style="width:100px;height: 50px" v-bind:src="'/premises/download?name='+scope.row.pic">
</template>