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

时间:2022-07-26
本文章向大家介绍java实现多个网络文件批量下载并压缩,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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")的方式验证

然后会自动弹出下载框框