/**
* 功能描述: 批量导出
*
* @param : typeContent (上传文件的路径) userName(需批量下载的用户名)
* @author Larissa
* @date 2020/1/14 14:42
*/
@RequestMapping("outAnnexAll")
@ResponseBody
public void outAnnexAll(HttpServletRequest request, HttpServletResponse response, String typeContent, String userName) {
//响应头的设置
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
//设置压缩包的名字
String billname = "人事档案-" + userName;
String downloadName = billname + ".zip";
response.setHeader("Content-Disposition", "attachment; fileName=" + new String((downloadName).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
ZipOutputStream zipos = null;
DataOutputStream os = null;
InputStream is = null;
try {
//设置压缩流:直接写入response,实现边压缩边下载
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
//循环将文件写入压缩流
/*将字符串转换为集合*/
String[] split = typeContent.split(",");
String basePath = "";
if (System.getProperty("os.name").toLowerCase().startsWith("win")) {//windows系统
basePath = properties.getProperty("windows.path").trim();
} else if (System.getProperty("os.name").toLowerCase().startsWith("lin")) { //linux
basePath = properties.getProperty("linux.path").trim();
} else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
// mac os
basePath = System.getProperty("user.home") + properties.getProperty("mac.path").trim();
}
for (int i = 0; i < split.length; i++) {
String filePath = basePath + File.separator + split[i];
System.out.println("filePath===" + filePath);
File file = new File(filePath);
if (!file.exists()) {
//先设置编码
response.setContentType("text/html;charset=UTF-8");
try {
response.getWriter().write("<script type=\"text/javascript\">alert('文件不存在或已被移动');window.history.back();window.close(); </script>");
} catch (IOException e) {
log.error(e.getMessage(), e);
}
} else {
//添加ZipEntry,并ZipEntry中写入文件流
zipos.putNextEntry(new ZipEntry(userName+"/"+file.getName()));//里面的一定为目录,否则虽下载成功,但不能查看
os = new DataOutputStream(zipos);
is = new FileInputStream(file);
//一定要这样,之前使用IoUtis.copy()方法,结果导致失败
byte[] b = new byte[1024*10];
int len =0;
while ((len = is.read(b))!=-1){
os.write(b,0,len);
}
}
}
} catch (IOException e) {
log.error(e.getMessage(),e);
} finally {
//切记关闭流(不关闭会产生bug,被检测出来会扣工资)
if (os != null) {
try {
os.flush();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
if (zipos != null) {
try {
zipos.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}