SpringBoot+VUE(Ant Design Vue)实现图片下载预览功能
目录
背景
1.后端实现下载接口
2.前端请求实现
第一步:导入api
第二步:请求接口
3.前端展示实现
4.实现效果展示
5.总结
背景
这段时间通过SpringBoot+VUE(Ant Design Vue)框架做了一个项目,但是在图片下载,展示的时候在网上搜了好多方法都解决不了,最后发现虽然图片能下载了,但是没有正确赋值给前端字段,所以今天把这个坑分享出来,以免各位踩坑!
1.后端实现下载接口
以下代码是前端请求图片地址,需要传入一个图片的唯一标识符
@RequestMapping(value = "/download", method = RequestMethod.GET)
@Transactional
public void download(Thing thing, HttpServletResponse response) throws IOException {
String fileUUID = thing.cover;
if(StringUtils.isEmpty(fileUUID)) {
return;
}
// 根据文件的唯一标识码获取文件
File destFile = new File(uploadPath + File.separator + "image" + File.separator + fileUUID);
// 设置输出流的格式
ServletOutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
response.setContentType("image/jpeg");
// 读取文件的字节流
os.write(FileUtil.readBytes(destFile));
os.flush();
os.close();
}
2.前端请求实现
以下是代码部分,
第一步:导入api
import { downloadApi } from '/@/api/thing';
第二步:请求接口
需要注意的是前端请求代码需要放在请求列表for循环里面
await downloadApi({
cover: item.cover,
})
.then((res) => {
item.cover = res.data;
const reader = new FileReader();
reader.onload = (e) => {
this.cover = e.target.result; // 将base64编码的图片数据存储在Vue组件的data属性中
};
reader.readAsDataURL(new Blob([res.data], { type: 'image/jpeg' })); // 根据实际情况调整MIME类型
})
.catch((err) => {
console.log(err);
});
item.cover = BASE_URL + '/api/thing/download?cover=' + item.cover;
3.前端展示实现
这一步是需要在table里面赋值属性
<template v-if="column.key === 'cover'">
<img :src="record.cover" style="width: 50px; height: 50px" />
</template>
4.实现效果展示
5.总结
以上步骤就是vue前端通过请求后端二进制流预览图片的全过程,上面这个方法不止图片,视频都可以用这种方法进行预览。
喜欢的小伙伴请留下一个免费的点赞,关注,评论吧!