数据模型:
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);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("D:\\img\\"+filename);try {file.transferTo(picFile);} catch (IOException e) {throw new RuntimeException(e);}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>