HTML+JavaScript+SpringBoot:实现PDF文件批量下载功能
前言
本文主要分享了实现 PDF 文件批量下载的 HTML+JavaScript+SpringBoot 全套代码
大家觉得有用的话麻烦点赞+收藏哦!谢谢您
一、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)
}
二、SpringBoot
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();
}
}
}