当前位置: 首页 > news >正文

springboot后端返回图片,vue前端接收并显示的解决方案

后端图片数据返回

后端通过二进制流的形式,写入response中

controller层

    /*** 获取签到二维码*/@GetMapping("/sign-up-pict")public void signUpPict(Long id, Long semId, HttpServletResponse response) throws NoSuchAlgorithmException {signUpService.getImage(id, semId, response);}

service层

/*** 返回二维码** @param id    教师id* @param semId 课程id* @param response* @return*/@Overridepublic void getImage(Long id, Long semId, HttpServletResponse response) throws NoSuchAlgorithmException {// 保存生成的二维码图片BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 业务逻辑, 全部忽略删除了...// 设置返回数据类型response.setContentType("image/png");try {// 将图片数据写入out中OutputStream out = response.getOutputStream();// 将图片数据写入out中, 返回前端ImageIO.write(image, "png", out);out.close();}catch (IOException e) {throw new RRException(ErrorCode.IMAGE_GENERATE_FAILED);}}

前端axios接受数据

axios接受数据时,responseType 默认返回数据类型是 json,必须将其改为返回数据类型 blob。否则axois无法正确解析数据。
这里的http.request是对axios的封装,把他当作axios用就行

return http.request<R<any>>("get",signModuleUrlApi(`/signup/sign-up-pict?id=${id}&semId=${semId}`),// 一定要加, 否则axios会把二进制数据处理为json{responseType: "blob"});

vue界面渲染

<template><!-- 忽略其它部分代码, 下面这货显示图片--><el-image :src="url" lazy />
<\template><script>const url = ref();// 发送请求signApi.signUpPict(id, semId.value).then(res => {const blob = new Blob([res], { type: "image/png" });// 创建URL对象url.value = URL.createObjectURL(blob);},error => {console.log(error);ElMessage.error("系统错误, 无法生成二维码");});};
<\script>

注意事项

  1. 后端接口,最好不要有返回值,如果你设置了response.setContentType(“image/png”),很有可能在返回数据的时候出现序列化错误的bug
  2. 后端接口,最好对response的contentType设置一下,不然容易出现一些奇怪的bug
  3. 前端axios一定要设置responseType: “blob”,否则axios会把数据当成json处理

学习文章

https://zhuanlan.zhihu.com/p/474173086
https://www.jianshu.com/p/12fea9987c2d

http://www.lryc.cn/news/134958.html

相关文章:

  • 算法|Day46 动态规划14
  • 宠物小程序开发攻略:五分钟教你打造宠物店小程序
  • open suse 15.5(任意版本) 使用阿里云的repo
  • 第一篇:编写 Hello World 程序
  • python 打印沁园春 雪 居中对齐 文本对齐
  • 在 IDEA 中使用 Git开发 图文教程
  • NodeJs导出PDF
  • 内核编译机制
  • 机器人TF坐标系变换与一些可视化工具的应用
  • c++ 友元 运算符重载详解
  • DataWhale 机器学习夏令营第三期
  • 回归预测 | MATLAB实现BES-LSSVM秃鹰搜索算法优化最小二乘支持向量机多输入单输出回归预测(多指标,多图)
  • python分析实战(4)--获取某音热榜
  • Java根据List集合中的一个字段对集合进行去重
  • (AtCoder Beginner Contest 315)
  • API 接口选择那个?RESTful、GraphQL、gRPC、WebSocket、Webhook
  • 「Python|音视频处理|环境准备」如何在Windows系统下安装并配置音视频处理工具FFmpeg
  • 软考高级架构师下篇-12层次式架构设计理论与实践
  • 234. 回文链表
  • LInux之例行工作
  • C++,从“hello world“开始
  • /root/.ssh/config line 2: Bad protocol 2 host key algorithms ‘+ssh-rsa‘.
  • mac m1上系统内录内部声音的方法/无需安装Blackhole
  • 数字人学习目录
  • PHP 房产网站系统Dreamweaver开发mysql数据库web结构php编程计算机网页项目
  • 0基础入门代码审计-2 Fortify初探
  • qiiuzhiji4
  • 构建 NodeJS 影院微服务并使用 docker 部署【01/4】
  • 变频器和plc之间无线MODBUS通讯
  • 【云原生】3分钟快速在Kubernetes1.25部署Prometheus2.42+Grafana9.5.1+Alertmanager0.25