springboot 单个文件下载,多个文件打zip包

 需求:

附件表存的报表的附件信息,包括地址,名称后缀,用户展示端选择一个文件或者多个文件进行下载。

思路:

1、展示端获取附件id一个或者多个传到后台

2、后台获取附件信息,判断附件信息个数,确定是否达成zip包

3、将压缩文件存在临时文件中

4、用流的方式输出到浏览器

代码:


/**
 * 下载文件
 * @param ids
 */
function downLoadFile(ids) {

    var form = $("<form  id='excel_temp_download_form' method='get'></form>");
    form.attr("action",common.domainName+'/api-i/inspection/report/load');
    form.append($("<input type='text' name='ids' value='" + ids + "' />"));
    $(document.body).append(form);
    form.submit();
    $('#excel_temp_download_form').remove()
}

 

/**
 * 单个或者多个下载
 * @param response
 * @param ids
 * @throws IOException
 */
@RequestMapping("/load")
public void downLoad(HttpServletResponse response, @RequestParam("ids") List<String> ids)
        throws IOException {

    reportService.download(response,ids);

}
/**
     * 单个或者批量下载文件
     *
     * @param response
     * @param ids
     */
    public void download(HttpServletResponse response,
                         List<String> ids) throws IOException {

        ZipEntry zipEntry = null;

        // 获取指定ID的附件列表
        List<Attachment> list = attachmentRepository.findAllByIdIn(ids);

        String path = "";
        String name = "";
        if(list.size() == 1){
            Attachment attachment = list.get(0);
            path = attachment.getPath();
            name = attachment.getName() + attachment.getSuffix();
        } else {
            long nowTime = new Date().getTime();
            name = "attachment_" + nowTime + ".zip";
            path = fileToZip(list,name);
        }

        OutputStream out = null;
        BufferedInputStream br = null;

        try {

            String fileName = URLEncoder.encode(name, "UTF-8");
            br = new BufferedInputStream(new FileInputStream(path));
            byte[] buf = new byte[1024];
            int len = 0;
            response.reset(); // 非常重要
            // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0)
                out.write(buf, 0, len);
            out.flush();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            br.close();
            out.close();
        }
    }
/**
     * 将文件放入zip文件中
     * @param list
     * @param fileName
     * @return
     */
    public static String fileToZip(List<Attachment> list,String fileName) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;

        // 临时目录 C:\Users\ADMINI~1\AppData\Local\Temp\
        String path = System.getProperty("java.io.tmpdir")+ fileName;
        try {
            File zipFile = new File(path );
            // 如果存在该zip文件,则删除
            zipFile.deleteOnExit();

            // 创建一个新文件
            zipFile.createNewFile();

            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(new BufferedOutputStream(fos));
            byte[] bufs = new byte[1024 * 10];
            for (Attachment attachment: list) {

                File subFile = new File(attachment.getPath());
                //如果文件不存在,则不添加到zip包中
                if (!subFile.exists()){
                    continue;
                }
                // 文件名增加时间戳避免重复
                String subFileName =  attachment.getName() + "-" + new Date().getTime() +
                        attachment.getSuffix();
                //创建ZIP实体,并添加进压缩包
                ZipEntry zipEntry = new ZipEntry(subFileName);
                zos.putNextEntry(zipEntry);
                //读取待压缩的文件并写进压缩包里
                fis = new FileInputStream(subFile);
                bis = new BufferedInputStream(fis, 1024 * 10);
                int read = 0;
                while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                    zos.write(bufs, 0, read);
                }
            }
            System.out.println("压缩成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关闭流
            try {
                if (null != bis) bis.close();
                if (null != zos) zos.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        return  path;
    }

 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值