controller
public void exportUserFaces(HttpServletRequest request,HttpServletResponse response,@RequestBody UserInfoDTO userQueryDTO) throws IOException{
try {
userUploadService.exportUserFaces(userQueryDTO,request,response);
}catch (Exception e){
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<>();
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}
service
public void exportUserFaces(UserInfoDTO userQueryDTO,HttpServletRequest request, HttpServletResponse response) {
// 符合查询条件的员工信息
List<UserInfoVO> userInfoVOList = userInfoService.pages(userQueryDTO).getRecords();
// 移除没有头像图片的员工
userInfoVOList.removeIf(userInfoVO -> ObjectUtil.isEmpty(userInfoVO.getFaceId()));
// 员工工号
List<String> pictureNames = userInfoVOList.stream().map(UserInfoVO::getUserCode).collect(Collectors.toList());
// 图片全路径数组
List<String> files = userInfoVOList.stream().map(UserInfoVO::getFaceId).collect(Collectors.toList());
// 下载图片并压缩成zip文件
createZipFile(request,response,files,pictureNames);
}
下载图片,打包压缩文件的方法在这里!!
/***
* 下载员工头像图片,并打包成压缩文件.zip
* @param request request
* @param response response
* @param files 员工头像图片的全路径
* @param fileNames 员工工号
*/
public void createZipFile(HttpServletRequest request, HttpServletResponse response, List<String> files, List<String> fileNames){
try {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//文件的名称,转换中文否则可能会产生乱码
String downloadFilename = URLEncoder.encode("员工头像" + df.format(LocalDateTime.now()) +".zip", "UTF-8");
// 指明response的返回对象是文件流
response.setContentType("application/octet-stream");
// 设置在下载框默认显示的文件名
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
for (int i=0;i<files.size();i++) {
URL url = new URL(picturePath + files.get(i));
// 图片重命名
zos.putNextEntry(new ZipEntry(fileNames.get(i)+".jpg"));
InputStream fis = url.openConnection().getInputStream();
byte[] buffer = new byte[1024 * 5];
int r;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
zos.flush();
zos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}