实战之oss附件批量下载---springboot 实现压缩阿里云oss附件并下载

实战之oss附件批量下载,借鉴网上一些案例,但是没有达到预期效果,结合项目需求。实现远程将oss上的文件进行压缩,并提供给前端用户下载,经过测试完美实现该功能。

@PostMapping("downLoadZip")
    public void downLoadZip(@RequestBody CourseDetailVo detailVo,
                            HttpServletResponse response,
                            @RequestParam(value = "customFileName", required = false, defaultValue = "default.zip") String customFileName) throws IOException {
        List<AttachZipDto> objectNames = detailVo.getZipDtoList();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
            for (AttachZipDto objectName : objectNames) {
                String fileUrl = objectName.getFileOssUr();
                String extension = TouUtil.getFileExtension(objectName.getFileOssUr());
                if (fileUrl.startsWith("/")) {
                    fileUrl = fileUrl.substring(1);
                }
                try (InputStream inputStream = ossUtil.getFileInputStream(fileUrl)) {
                    zipOut.putNextEntry(new ZipEntry(objectName.getFileName()+"."+extension));
                    IOUtils.copy(inputStream, zipOut);
                    zipOut.closeEntry();
                } catch (OSSException | IOException e) {
                    // 处理从 OSS 获取文件时发生的异常
                    throw new RuntimeException("Failed to retrieve file from OSS", e);
                }
            }
            // 设置HTTP响应头
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(customFileName, StandardCharsets.UTF_8.toString()) + "\"");
            // 将压缩文件写入HTTP响应
            try (OutputStream outputStream = response.getOutputStream()) {
                byteArrayOutputStream.writeTo(outputStream);
            }
        } catch (IOException e) {
            // 处理 ZIP 创建或写入响应时的异常
            throw e;
        }

欢迎点赞、转发、收藏。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值