本方法是使用el-upload上传文件至本地文件夹中,再用WebMvcConfigurer对匹配的URL进行拦截,映射到本地文件夹来展示和下载图片。
el-upload实现图片回显:
template页面显示部分:
<el-form-item label="头像">
<el-upload class="avatar-uploader"
:show-file-list="false"
:action="uploadUrl"
:headers="tokenInfo"
ref="upload"
:on-success="handleAvatarSuccess">
<img v-if="dataForm.imgUrl"
:src="dataForm.imgUrl"
class="avatar">
<i v-else
class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
js部分:
export default {
data () {
return {
visible: false,
file: null,
}
}
}
methods: {
handleAvatarSuccess (raw,file) {
this.dataForm.imgUrl = URL.createObjectURL(file.raw)
}
}
上传图片后通过URL.createObjectURL()方法生成一个图片URL,并将img标签的src属性指向这个URL
编写配置类:
首先建立配置类继承WebMvcConfigurer并重写addResourceHandlers方法:
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String filePath = System.getProperty("user.dir") + "/src/main/resources/static/img/";
System.out.println(filePath);
registry.addResourceHandler("/static/**")
.addResourceLocations("file:" + filePath);
//addResourceHandler()里的是虚拟路径,addResourceLocations()里加的是真实路径
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
addResourceHandler()里的是虚拟路径,addResourceLocations()里加的是真实路径
然后在本地文件夹里添加一张图片,启动项目测试能否成功显示图片;
可见,通过虚拟路径映射成功显示本地图片,开始下一步操作。
后端保存图片信息
后端控制器:
@PostMapping("/upload")
public R upload(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String hToken = UUID.randomUUID().toString();
String HeadName = hToken + fileName;
String filePath = System.getProperty("user.dir") + "/src/main/resources/static/img/";
String fileAddress = filePath + HeadName; //文件真实路径
try {
file.transferTo(new File(fileAddress));
} catch (Exception e) {
}
return R.ok().put("url", "http://localhost:8080/static/" + HeadName);
//文件映射路径
}
保存文件到静态目录下,并返回该文件映射路径;
前端代码:
export default {
data () {
return {
uploadUrl: this.$http.adornUrl('/tb/img/upload'),
}
}
}
methods: {
handleAvatarSuccess (res, file) {
this.dataForm.imgUrl = URL.createObjectURL(file.raw)
this.dataForm.img = res.url
}
}
将返回的映射路径保存到表单中以待后续处理。
前端展示图片,下载图片
前端页面代码:
<el-table-column label="图片"
v-bind="dataList.img"
header-align="center"
align="center">
<template slot-scope="scope">
<img :src="scope.row.imgUrl"
class="avatar-navbar"
v-if="scope.row.imgUrl">
</template>
<el-button type="text"
size="small"
@click="download(scope.row.imgUrl,scope.row.imgName)">下载</el-button>
</el-table-column>
这里的imgUrl就是上面返回的url
前端js代码:
methods: {
download (url, fileName) {
this.$http({
url: this.$http.adornUrl('/common/download'),
method: 'post',
responseType: 'blob',
params: {
'url': url,
'name': fileName,
}
}).then(res => {
console.log(res)
if (res.data.size > 0) {
var blob = new Blob([res.data]);
var href = URL.createObjectURL(blob);
var downloadElement = document.createElement('a');
downloadElement.href = href;
downloadElement.download = fileName + "." + 'JPG'; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
} else {
this.$message.error('文件或图片失效请重新上传')
}
});
},