HTML+JavaScript+SpringBoot: Realize batch download function of PDF files

HTML+JavaScript+SpringBoot: Realize batch download function of PDF files


foreword

This article mainly shares the HTML+JavaScript+SpringBoot full set of codes for batch downloading of PDF files

If you find it useful, please like + bookmark! thank you


1. HTML+JavaScript

content.html

//实现批量下载的按钮
<button class="btn btn-primary" type="button" onclick="xzAllws('{ 
        {contentItem.id}}')" style="font-size: 12px">PDF文件批量下载</button>
content.js

function xzAllws(id) {
    
    
    var url = '/xzAllws.do?contentid=' + id;
    window.open(url)
}

2. Spring Boot

download.java

@RequestMapping(value = "/xzAllws.do", method = RequestMethod.GET)
@ResponseBody
public void xzAllws(HttpServletRequest request, HttpServletResponse response, @RequestParam("contentid") Integer contentid) throws Exception {
    
    
    DynamicDataSource.router("文书信息库");//切换到文书信息库
       //filePath是下载路径集合
       //fileName是文件名称
    List<String> paths = new LinkedList<>();
    List<String> childName = new LinkedList<>();
    //这里省去了filePath和fileName的定义过程
    //需要自己定义下载路径集合和文件名称
    String fileName = "PDF文件批量下载压缩包"+ ".zip";
    DownloadUtils.downloadZip(paths,childName,fileName,response,request);
}
DownloadUtils.java

  /**
  * 下载zip
  */
 public static void downloadZip(List<String> paths, List<String> childName, String fileName, HttpServletResponse response, HttpServletRequest request){
    
    
     ZipOutputStream zos = null;
     BufferedInputStream br = null;
     try {
    
    
         //文件的名称
         response.reset();
         //设置格式
         response.setContentType("application/x-msdownload");
         response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
         //ZipOutputStream来对文件压缩操作
         zos = new ZipOutputStream(response.getOutputStream());
         //循环下载文件,并将之放到ZipOutputStream中
         for (int i = 0 ; i < paths.size(); i ++) {
    
    
             String name = childName.get(i);
             String path = paths.get(i);
             //filePath是下载路径集合
             //fileName是文件名称
             zos.putNextEntry(new ZipEntry(name));
             br=new BufferedInputStream(new FileInputStream(path));
             byte[] buffer = new byte[1024];
             int r = 0;
             while ((r = br.read(buffer)) != -1) {
    
    
                 zos.write(buffer, 0, r);
             }
             br.close();
         }
         zos.flush();

     } catch (IOException e) {
    
    
        e.printStackTrace();
     }finally {
    
    
         try {
    
    
             zos.close();
             br.close();
         } catch (IOException e) {
    
    
             System.out.println();
         }
     }
 }

Guess you like

Origin blog.csdn.net/qq_46119575/article/details/130148594