当前位置:   article > 正文

springboot 以IO流形式返回给前端_springboot fegin返回io流

springboot fegin返回io流

1、Controller

@ApiOperation(value = "IO流返回给前端")
@GetMapping("fileView")
public void fileView(@ApiParam(value = "文件路径", required = true) @RequestParam String fileUrl, HttpServletResponse response) {
    fileService.fileView(fileUrl, response);
}
  • 1
  • 2
  • 3
  • 4
  • 5

2、Service

    /**
     * 以IO流的形式返回给前端
     *
     * @param fileUrl  文件路径
     * @param response resp
     */
    public void fileView(String fileUrl, HttpServletResponse response) {
        // 读取文件名 例:yyds.jpg
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        try (FileInputStream inputStream = new FileInputStream(fileUrl);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] data = new byte[1024];
            // 全文件类型(传什么文件返回什么文件流)
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Accept-Ranges", "bytes");
            int read;
            while ((read = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, read);
            }
            // 将缓存区数据进行输出
            outputStream.flush();
        } catch (IOException e) {
            log.error("失败", e);
            throw new Exception("exception");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

3、另外一种写法

如果为小文件,则可直接写入,无须循环,效率更高

byte[] data = new byte[inputStream.available()];
inputStream.read(data);
response.set
......
outputStream.write(data);
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/842523
推荐阅读
相关标签
  

闽ICP备14008679号