后端返回图片的stream流,前端怎么显示出图片

 /**
     * 礼包图片下载
     * @return
     */
    @GetMapping(value= "/dowloadPacketImage")
    public void dowloadPacketImage( HttpServletResponse response, String packetPicPath){
        if(StringUtils.isBlank(packetPicPath)) {
            logger.info("礼包图片路径为空");
            return;
        }
        String imgName = packetPicPath.substring(packetPicPath.lastIndexOf(File.separator) + 1);
        DownloadUtil.downloadFile(response, packetPicPath, imgName);
    }
  public static void downloadFile(HttpServletResponse response, String filePath, String fileName) {
        OutputStream responseStream = null;
        try {
            byte[] resultBytes = FileUtils.readFileToByteArray(new File(filePath));
            // response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

            responseStream = response.getOutputStream();
            responseStream.write(resultBytes, 0, resultBytes.length);

            responseStream.flush();
            response.flushBuffer();
        } catch (Exception e) {
            if (null != responseStream) {
                try {
                    responseStream.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
阅读 13.7k
2 个回答
  1. 如果你的那个返回流的地址是可以直接 get 请求的,那么就用 <img /> 标签,src 属性直接设置返回流的地址.
  2. 如果是其它接口,那就现在 js 里把流拿到,转成 blob,再赋值给 <img /> 标签的 src 属性

直接返回页面里显示的图片的话

  1. response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); 去掉,这个是文件下载
  2. "application/octet-stream" 换成 "image/图片格式
  3. 页面上用<img src="接口地址"/>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题