Java后端传图片字节流到Vue前端显示

Java将本地图片转字节流byte[]数组

  • service
@Override
    public byte[] image2bytes(String imgSrc) throws Exception {
        FileInputStream fin = new FileInputStream(imgSrc);
        //可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
        byte[] bytes  = new byte[fin.available()];
        //将文件内容写入字节数组,提供测试的case
        fin.read(bytes);
        fin.close();
        return bytes;
    }
  • controller
@ApiOperation(value = "")
    @PostMapping("getImgBytes")
    @ResponseBody
    public CommonResult<byte[]> getImgBytes(@RequestBody JSONObject jsonObject) throws Exception {
        Object obj = jsonObject.get("imgStr");  //前端传来的是json对象,需要去除字符串
        String str = obj.toString(); //Object对象转String
        System.out.println(str);
        byte[] b = fragmentService.image2bytes(str);
        return CommonResult.success(b);
    }

Vue发送本地图片url给后端,获取图片字节流并显示图片

  • 将url发送给后端,获取返回的字节流(其中imgPath为图片url,imgBase存转化的字节流)
showImgByte() {
      this.$http.post('http://localhost:8080/fragment/getImgBytes', {
        imgStr: this.imgPath
      }).then((response) => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: '成功'
          })
          console.log(response.data)
          this.imgBase = response.data.data
          console.log(response.data.data)
        } else {
          this.$message({
            type: 'error',
            message: '失败'
          })
        }
      })
    },
  • 组件上显示图片
    template标签中写
 <el-image
   :src="picUrl"
   :fit="fit"
 />

script标签中的data(){}中写

data() {
    return {
      imgPath: '',  //存图片url
      excelPath: '',
      picUrl: '',  //img标签显示
      fit: 'fill',  //img填充方式
      imgBase: '' //存图片字节流
    }
  },

显示图像的button绑定的方法中写,点击即可显示图像

 showImg() {
      this.picUrl = 'data:image/png;base64,' + this.imgBase
    },

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值