public void ZIP_download_BCJ(HttpServletResponse response, HttpServletRequest request,String bCJ_NO_ZIP)throws Exception {
//bCJ_NO_ZIP 个人使用,具体场景具体分析
//System.out.println(filePath);
String zipFilePath = null;
try {
// ************************************************
// 站點的物理路徑:request.getServletContext().getRealPath("/") = "C:\apache-tomee-plus-7.0.2\wtpwebapps\wWMS\"
// ************************************************
String filePath = request.getServletContext().getRealPath("/") + File.separator;
zipFilePath = filePath + UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0, 11) + ".zip";
File zip = new File(zipFilePath);
JSONArray jArray = GetPATH_PIC1(bCJ_NO_ZIP);
//GetPATH_PIC1(bCJ_NO_ZIP)是个人方法,获取文件的所造路径,不同通用,
File srcfile[] = new File[jArray.length()];
for (int j = 0, n1 = jArray.length(); j < n1; j++) {
srcfile[j] = new File(jArray.getJSONObject(j).getString("FILEPATH"));
}
//jArray.getJSONObject(j).getString("FILEPATH") 这里的注意点是获取到有关文件的物理路径,方法不唯一,
ZipFiles(srcfile, zip);
response.setContentType("application/zip");
response.setHeader("Location", zip.getName());
response.setHeader("Content-Disposition", "attachment; filename=" + zip.getName());
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(zipFilePath);
byte[] buffer = new byte[1024];
int q = -1;
while ((q = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, q);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} finally {
new File(zipFilePath).delete();//如果不删除,生成的文件会一直累积在后台的文件夹里
//放在finally的是无论是否中间的代码是否有错,最后一律执行删除文件操作
}
}
//********************************************************************************************************************
public void ZipFiles(File[] srcfile, File zipfile) {
byte[] buf = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.length; i++) {
FileInputStream in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
前端下载方法 (gBaseURL +strURL 是能够连接到后台的路径,具体场景具体分析)
window.location.href = gBaseURL +strURL;