@RequestMapping("/batchDownLoad")
@ResponseBody
public void batchDownLoad(HttpServletRequest request,HttpServletResponse response,String fileNames) {
Map<String,String> map=new HashMap<>();
String[] files=fileNames.split(",");
for(String fileName:files){
map.put(fileName,SysFileUtils.getFilePath()+ fileName);
String fileName = "批量下载.zip";
String realPath = request.getSession().getServletContext().getRealPath("/");
try {
zipFile(map,realPath,fileName);
realPath = realPath + fileName;
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(realPath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文件打包
* @author niuyuhui
* @param map
* @param rootPath
* @param fileName
* @throws Exception
*/
public void zipFile(Map<String,String> map, String rootPath, String fileName) throws Exception{
File zipFile = new File(rootPath + "/" + fileName);
if (zipFile.exists()) {
zipFile.delete();
}
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(rootPath + "/" + fileName));
ZipEntry ze = null;
byte[] buf = new byte[1024];
int readLen = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
ze = new ZipEntry(entry.getKey());
zos.putNextEntry(ze);
String absoluteFileName = entry.getValue();
InputStream is = new BufferedInputStream(new FileInputStream(absoluteFileName));
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
}
zos.close();
}