/**
* 将附件打包下载
* @param list
* @param zipName
* @param session
* @param response
* @throws IOException
*/
public void zipDownload(List<TCommonAtta> list, String zipName, HttpSession session, HttpServletResponse response)
throws IOException {
if(list.isEmpty()){
return;
}
if(!zipName.contains(".zip")){
zipName += ".zip";
}
int len;
int countIndex = 0;
byte[] buf = new byte[1024];
List<String> li = new ArrayList<String>();
File zipFile = new File(session.getServletContext().getRealPath("/") + "/myzip.zip");
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile));
for (TCommonAtta atta : list) {
// 附件名称重复,则修改附件名称
String attaName = atta.getAttaName();
if (li.contains(attaName)) {
attaName += String.valueOf(countIndex);
countIndex++;
}
li.add(attaName);
String attaPath = atta.getAttaPath();
InputStream in = FastDFSFileUtils.downloadFile(attaPath);
zout.putNextEntry(new ZipEntry(attaName + "." + atta.getAttaSuffix()));
while ((len = in.read(buf)) > 0) {
zout.write(buf, 0, len);
}
zout.closeEntry();
in.close();
}
zout.close();
zipName = new String(zipName.getBytes(), "ISO-8859-1");
FileInputStream zipInput = new FileInputStream(zipFile);
OutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
while ((len = zipInput.read(buf)) != -1) {
out.write(buf, 0, len);
}
zipInput.close();
out.flush();
out.close();
// 删除压缩包
zipFile.delete();
}
public void download (String attaPath, String filename, HttpServletRequest request, HttpServletResponse response)
throws IOException{
InputStream ips = null;
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Type", "application/octet-stream");
ServletOutputStream out = response.getOutputStream();
// 获得浏览器信息并转换为大写
String agent = request.getHeader("User-Agent").toUpperCase();
try {
if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) { // IE浏览器和Edge浏览器
filename = URLEncoder.encode(filename, "UTF-8");
} else { // 其他浏览器
filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
}
response.setHeader("content-disposition", "attachment;filename=" + filename);
ips = FastDFSFileUtils.downloadFile(attaPath);
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = ips.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
ips.close();
}
}