spring通过response响应流下载文件

 /**
     * 文件下载
     * @param fileId
     */
    @Override
    public void downloadMaterial(Long fileId, HttpServletResponse response) throws IOException {
    //获取文件存储路径,此步骤省略,自己根据需求编写,或者直接把路径放在入参进行传递
        //文件存储路径
        String filePath;
        File file = new File(filePath);
        if (!file.exists()){
            throw new ServiceException("文件不存在");
        }

        // 对文件名进行 URL 编码  commonSysFile.getOriginalFilename()文件原始名:文件名.后缀
        String encodedFileName = URLEncoder.encode(commonSysFile.getOriginalFilename(), "UTF-8");
        // 防止一些浏览器(如 Chrome)将 '+' 字符解码为空格,替换它
        encodedFileName = encodedFileName.replaceAll("\\+", "%20");
        // 设置响应头
        response.reset();
        response.setCharacterEncoding("UTF-8");
        // 获取文件的 MIME 类型  对.png类型比较友好
            String contentType = Files.probeContentType(Paths.get(filePath));
            if (contentType == null) {
                contentType =MediaType.APPLICATION_OCTET_STREAM_VALUE;  // 默认为二进制流
            }

        // 设置 Content-Disposition,指定为附件下载,并附上文件名  filename*=utf-8考虑浏览器兼容问题,避免文件名中文乱码
        response.addHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=utf-8''" + encodedFileName);
        // 读取文件并将其写入到响应输出流 filePath文件存储路径:D:/abd/bcd/文件名.后缀
        try (InputStream is = new BufferedInputStream(Files.newInputStream(Paths.get(filePath)))) {
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

附上postman测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值