栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 以IO流形式返回给前端

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 以IO流形式返回给前端

1、Controller
@ApiOperation(value = "IO流返回给前端")
@GetMapping("fileView")
public void fileView(@ApiParam(value = "文件路径", required = true) @RequestParam String fileUrl, HttpServletResponse response) {
    fileService.fileView(fileUrl, response);
}
2、Service
    
    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");
        }
    }
3、另外一种写法

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

byte[] data = new byte[inputStream.available()];
inputStream.read(data);
response.set
......
outputStream.write(data);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684851.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号