首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java实现多个网络文件批量下载并压缩

java实现多个网络文件批量下载并压缩

作者头像
java攻城狮
发布2020-10-10 16:33:33
5K0
发布2020-10-10 16:33:33
举报
文章被收录于专栏:个人积累个人积累

java实现多个网络文件批量下载并压缩

1. 使用场景

文档管理模块,列表中显示的记录的每日文件上传保存的记录.每条数据中有一个字段存放了文件的存储地址文件服务器上

现在需要对列表数据批量下载,将多个文件一起下载并存放到一起通过zip压缩包的形式下载到浏览器

2. 开发步骤

思路: 先将多个文件单独一个个下载存放在磁盘的某个位置,然后再将该文件数据进行压缩.

2.1 逐个下载并存放至指定路径

applicationProperties.getUploadPath();读取配置文件指定的下载地址.

读取配置文件参见

public List<String> downloadToLocal(List<String> urls){
        // applicationProperties 来源于配置文件读取类,获取本地指定的临时存放区域
        String rootPath = applicationProperties.getUploadPath();
        File file = new File(rootPath);
        if(!file.exists()){
            file.mkdirs();
        }
        List<String> fileList = new ArrayList<>();
        try {
            File f = null;
            FileOutputStream fos = null;
            ZipOutputStream zos = null ;
            for(String url : list){
                String fileName = url.substring(url.lastIndexOf("/")+1);
                byte[] bytes = fastDFSClient.downloadFile(url);
                fileList.add(rootPath + "//" + fileName);
                f = new File(rootPath + "//" + fileName);
                fos = new FileOutputStream(f);
                fos.write(bytes,0,bytes.length);
            }
            zipFile(fileList,response);
            fos.flush();
            fos.close();
            return fileList;
        } catch (Exception e){
            throw new BadRequestAlertException("Batch download file failed",this.getClass().getSimpleName(),"Batch download file failed");
           
        }
}
2.2 将多个文件放到文件夹并压缩在浏览器下载
public void zipFile(List<String> fileUlr, HttpServletResponse response){
        byte [] bytes = new byte[1024];

        String zipFileName= "图片压缩下载";
        BufferedOutputStream bos = null ;
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());

            response.reset();
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + zipFileName + ".zip");

            out = new ZipOutputStream(bos);
            for(String str :  fileUlr) {
                File  file = new File(str);
                if(!file.exists()){
                    log.error("文件被删除");
                    continue;
                }
                ZipEntry zEntry = new ZipEntry(file.getName());
                out.putNextEntry(zEntry);
                in = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int read = 0;
                while((read = in.read(buffer)) != -1){
                    out.write(buffer, 0, read);
                }
            }
            out.close();
            bos.close();
            log.info("========= 文件压缩成功 ============");
        } catch (Exception e){
            throw new BadRequestAlertException("zipFile_error" ,this.getClass().getSimpleName(),"zipfile_download_error");
        }
    }
2.3 指定本地路径直接下载
/**
     *  下载文件到制定路径
     * @param fileList
     */
    public void zipFile(List<String> fileList){

        String zipName ="批量下载.zip";
        String zipPath = applicationProperties.getUploadPath() + "//" + zipName;

        BufferedInputStream bis =null;
        try {
            ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
            for(String str :  fileList) {
                File  file = new File(str);
                if(!file.exists()){
                    log.error("文件被删除");
                    continue;
                }
                ZipEntry zEntry = new ZipEntry(file.getName());
                zipOutput.putNextEntry(zEntry);
                bis = new BufferedInputStream(new FileInputStream(file));
                byte[] buffer = new byte[1024];
                int read = 0;
                while((read = bis.read(buffer)) != -1){
                    zipOutput.write(buffer, 0, read);
                }
            }
            zipOutput.finish();
            bis.close();
            zipOutput.close();

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

3. 测试

@ApiOperation(value = "批量下载文件")
    @GetMapping("/downloads")
    public void mutilFileDownLoad(
            @ApiParam(value = "文件路径 ,使用逗号拼接,",required = true) @RequestParam(value = "urls") String urls,
            HttpServletResponse response
    ){
      List<String> list = Arrays.asList(urls.split(","));
      List<String> filelist = downloadToLocal(list);
      zipFile(filelist);
    
    }
  1. 验证方式一 这种方式只能确保接口没有问题,但是点击链接下载的文件是乱码的
  2. 验证方式二 可以直接将请求的接口直接copy在浏览器 console 通过window.open("http://xxxxx")的方式验证

然后会自动弹出下载框框

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • java实现多个网络文件批量下载并压缩
    • 1. 使用场景
      • 2. 开发步骤
        • 2.1 逐个下载并存放至指定路径
        • 2.2 将多个文件放到文件夹并压缩在浏览器下载
        • 2.3 指定本地路径直接下载
      • 3. 测试
      相关产品与服务
      文件存储
      文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档