从文件服务器下载多个文件并打包返回给前端

这里封装了一个ZipUtil工具类,每个项目用到的OSS服务可能不一样,但是SDK都大差不差,只需要替换掉里面获取文件流的方法就可以了

/**
 * 文件打包下载
 *
 * @author zzt
 * @version v1.0.0
 * @date 2023/6/14 15:01
 */
@Slf4j
@Component
public class ZipUtils {

    private static OssClient ossClient;

    public ZipUtils(OssClient ossClient) {
        ZipUtils.ossClient = ossClient;
    }

    /**
     * 获取多个文件压缩下载
     *
     * @param zipFileName:压缩文件名称
     */
    @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"})
    public static void downloadZip(@NotNull List<FileVo> fileList, @NotBlank String zipFileName) {
        //获取resources文件夹的真实路径
        String path = ZipUtils.class.getClassLoader().getResource("temporary").getPath();
        String destFilePath = path + "/" + zipFileName + ".zip";
        File zipFile = new File(destFilePath);
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            byte[] buf = new byte[1024 * 4];
            for (FileVo fileVo : fileList) {
                
                //替换自己项目中的OSS方法   InputStream inputStream = ossClient.downloadFile(fileVo.getFileKey());
                zos.putNextEntry(new ZipEntry(fileVo.getFileName()));
                int len;
                while ((len = inputStream.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
            }
        } catch (Exception e) {
            log.error("FileUtils.downloadZip()压缩文件报错,报错原因:[{}]", e.getMessage(), e);
            throw new RuntimeException("压缩文件失败!");
        }
        //下载文件
        ZipUtils.downloadFile(destFilePath);
        if (zipFile.exists()) {
            zipFile.delete();
        }
    }

    /**
     * 下载模工具(resources下文件)
     *
     * @param filePath zip文件路径
     */
    @SuppressWarnings("ConstantConditions")
    public static void downloadFile(String filePath) {
        //获取response
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        //读取文件
        try (FileInputStream resourceAsStream = new FileInputStream(filePath);
             BufferedInputStream fis = new BufferedInputStream(resourceAsStream);
             OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) {
            //获取文件名
            String name = URLEncoder.encode(FileUtil.getName(filePath), "UTF-8").replaceAll("\\+", "%20");
            int available = fis.available();
            byte[] buffer = new byte[1024 * 4];
            int r;
            while (-1 != (r = fis.read(buffer))) {
                toClient.write(buffer, 0, r);
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + name);
            response.addHeader("Content-Length", "" + available);
            response.setContentType("application/octet-stream;charset=UTF-8");
            toClient.flush();
        } catch (Exception e) {
            log.error("FileUtils.downloadTemplateFile()下载文件报错,报错原因:[{}]", e.getMessage(), e);
            throw new RuntimeException("下载失败!");
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值