SpringBoot 批量下载阿里云文件,打ZIP包(URL,非OSS)

刚遇到个需求,

批量下载文件(这边用的阿里云的文件存储,所以有的都是文件的URL,不限文件类型)

下面是代码:

Controller:

@GetMapping("download")
    @ApiOperation("文件下载")
    public void download(@ApiIgnore @RequestParam String[] urls, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition",
                "attachment;filename=" +
                        new String("files.zip".getBytes("GB2312"),
                                "ISO-8859-1"));  // 需要编码否则中文乱码
        response.setContentType("application/zip;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        billFileService.download(urls, response.getOutputStream());
    }

Service:

/**
     * 文件下载
     * @param urls
     * @param outputStream
     */
    @Override
    public void download(String[] urls, ServletOutputStream outputStream) {

        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        InputStream in = null;
        HttpURLConnection conn = null;
        try {
            for(String urlPath : urls) {
                URL url = new URL(urlPath);
                conn = (HttpURLConnection)url.openConnection();
                //以Post方式提交表单,默认get方式
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                // post方式不能使用缓存
                conn.setUseCaches(false);
                //连接指定的资源
                conn.connect();
                in = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(in);

                ZipEntry entry = new ZipEntry(urlPath.substring(urlPath.lastIndexOf("/"), urlPath.length()));
                zipOutputStream.putNextEntry(entry);

                byte[] bt = new byte[4096];
                int read = 0;
                while((read = bis.read(bt)) != -1) {
                    zipOutputStream.write(bt, 0, read);
                }
                in.close();
                conn.disconnect();
            }
            conn.disconnect();
        } catch (Exception e) {
            throw new RenException("下载文件异常! \n" + e.getMessage());
        } finally {
            if(zipOutputStream != null) {
                try {
                    zipOutputStream.flush();
                    zipOutputStream.close();
                    outputStream.flush();
                    outputStream.close();

                } catch (Exception e) {
                    throw new RenException("下载文件关闭流异常!");
                }
            }
        }
   }
【注意】
while((read = bis.read(bt)) != -1) {
    zipOutputStream.write(bt, 0, read);
}

我之前是直接write(bt);

导致文件会损坏!

另外,关于前端的话,我没写,但是看了有推介用:

window.location.href = "/download";

要从阿里云oss下载文件,可以使用Java SDK提供的OSSClient类。以下是使用Spring Boot实现从阿里云oss下载文件的步骤: 1. 引入阿里云Java SDK和Spring Boot依赖 在pom.xml中添加以下依赖: ``` <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 配置阿里云oss参数 在application.properties或application.yml中添加以下阿里云oss参数: ``` aliyun.oss.endpoint=<your endpoint> aliyun.oss.accessKeyId=<your accessKeyId> aliyun.oss.accessKeySecret=<your accessKeySecret> aliyun.oss.bucketName=<your bucketName> ``` 3. 实现文件下载接口 在Spring Boot的Controller中添加文件下载接口,使用OSSClient类下载指定文件: ``` @RestController public class FileController { @Autowired private OSSClient ossClient; @GetMapping("/download") public void download(@RequestParam String objectName, HttpServletResponse response) throws IOException { OSSObject ossObject = ossClient.getObject(bucketName, objectName); InputStream inputStream = ossObject.getObjectContent(); response.setHeader("Content-Disposition", "attachment;filename=" + objectName); response.setContentType("application/octet-stream"); IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); } } ``` 在上面的例子中,我们使用了@RequestParam注解来获取文件名,然后使用OSSClient类下载文件。最后,使用response将文件返回给客户端。 注意:在使用完OSSClient后,需要及时关闭它以释放资源。可以在Spring Boot的配置类中添加@PreDestroy注解来关闭OSSClient: ``` @Configuration public class OSSConfig { @Value("${aliyun.oss.endpoint}") private String endpoint; @Value("${aliyun.oss.accessKeyId}") private String accessKeyId; @Value("${aliyun.oss.accessKeySecret}") private String accessKeySecret; @Value("${aliyun.oss.bucketName}") private String bucketName; @Bean public OSSClient ossClient() { return new OSSClient(endpoint, accessKeyId, accessKeySecret); } @PreDestroy public void destroy() { ossClient().shutdown(); } } ``` 以上就是使用Spring Boot从阿里云oss下载文件的步骤。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值