前台代码
//头工具栏事件
table.on('toolbar(test)', function(obj){
var checkStatus = table.checkStatus(obj.config.id);
var requestNos = [];
switch(obj.event){
case 'requestSeeInto':
var data = checkStatus.data;
// console.log(data);
for(var i=0;i<data.length;i++){
requestNos.push(data[i].ID);
}
};
var requestData = requestNos.join(",");
if(requestData==null||requestData==""){
layer.alert("请勾选文件序号");
return;
}
// console.log(requestData);
window.open("/dz_exchange/api/license/batchDownLoad?path="+encodeURI(requestData))
});
后台代码:
@RequestMapping(value = "/batchDownLoad", method = RequestMethod.GET)
public void batchDownLoad() throws Exception {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
HttpServletResponse response = requestAttributes.getResponse();
//这里是前台传的以逗号分隔的id 根据id去分别查询对应的path
String path = request.getParameter("path");
String[] split = path.split(",");
//响应头的设置
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.addHeader("Access-Control-Allow-Origin", "*");//解决跨域
//设置压缩包的名字
Date date = new Date();
String billname = "附件包-" + date.getTime();
String downloadName = billname + ".zip";
//返回客户端浏览器的版本号、类型
String agent = request.getHeader("USER-AGENT");
try {
//针对IE或者以IE为内核的浏览器:
if (agent.contains("MSIE") || agent.contains("Trident")) {
downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
} else {
//非IE浏览器的处理:
downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
}
} catch (Exception e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
//设置压缩流:直接写入response,实现边压缩边下载
ZipOutputStream zipos = null;
try {
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
} catch (Exception e) {
e.printStackTrace();
}
//循环将文件写入压缩流
DataOutputStream os = null;
//查询数据库获取文件信息
//遍历文件信息(主要获取文件名/文件路径等)
for (int i = 0; i < split.length; i++) {
//根据id数据库获取
// 文件路径
String filePath = addLicenseDao.queryFilepath(split[i]);
System.out.println("filePath===" + filePath);
File file = new File(filePath);
if (!file.exists()) {
throw new Exception();
} else {
try {
//添加ZipEntry,并ZipEntry中写入文件流
String fileName = file.getName();//.substring(0,authAttachmentDetail.getFileName().indexOf("."));
zipos.putNextEntry(new ZipEntry(fileName));
os = new DataOutputStream(zipos);
InputStream is = new FileInputStream(file);
byte[] b = new byte[100];
int length = 0;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
zipos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//关闭流
try {
os.flush();
os.close();
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}