主代码
@Override
public void downloadPayAgre(HttpSession session, HttpServletResponse response, HttpServletRequest request,
String realName) {
ZipOutputStream zos = null;
try {
String zipFilePath = "压缩包" + ".zip";
response.reset();
response.setCharacterEncoding("gb2312");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(zipFilePath.getBytes("UTF8"), "ISO-8859-1"));
zos = new ZipOutputStream(response.getOutputStream());
//查询文件信息
EcPayAgre ctPayAgre = ecPayAgreDao.findByRealName(realName);
addZip("", ctPayAgre.getRealName(),ctPayAgre.getSuffix(), ctPayAgre.getFileName(), zos);
//查询文件信息
EcPayFile ecPayFile = ecPayFileDao.findByCtpaId(ctPayAgre.getCtpaId());
addZip("", ecPayFile.getRealName(),ecPayFile.getSuffix(), ecPayFile.getFileName(), zos);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
zos.flush();
zos.close();
}catch (Exception e){
System.out.println("文件压缩失败");
}
}
}
1、esponse.setHeader(“Content-Disposition”, “attachment; filename=” + new String(zipFilePath.getBytes(“UTF8”), “ISO-8859-1”));这里的UTF8编码,在ie浏览器中压缩包名称有可能是乱码,可将其改变为GBK,就可以解决。
2、addZip("", ctPayAgre.getRealName(),ctPayAgre.getSuffix(), ctPayAgre.getFileName(), zos);第一个参数为空,则直接将文件放入压缩包中,“图片/”在压缩包中新建一个名为"图片"的文件夹,并将文件放入其中。第二个参数是文件在文件服务器上的名称,第三个参数是后缀名,第四个参数是文件名称。
调用方法
private void addZip(String path, String realName,String suffix,String fileName, ZipOutputStream zos) throws Exception{
if(realName==null||realName.equals("")){
return;
}
byte[] data=downloadFile(realName+"."+suffix);
zos.putNextEntry(new ZipEntry(fileName+"."+suffix));
if(data==null){
throw new BusinessException(fileName+"."+suffix+"下载失败");
}
zos.write(data);
zos.closeEntry();
}
//下载文件
private byte[] downloadFile(String realName){
AttachmentBean bean = new AttachmentBean();
bean.setFileName(realName);
IAttachmentService downAttachmentService = ExcectorAttachmentFacatory.getInstance().createDownService(bean);
downAttachmentService.setAttachmentBean(bean);
try{
Message message = downAttachmentService.execute();
if(message.isResult()) {
byte[] fileData = Base64.decodeBase64((String) message.getData());
byte[] data = GzipUtil.uncompress(fileData);
return data;
}else{
System.out.println("文件下载失败");
return null;
}
}catch (Exception e){
System.out.println("文件下载失败");
return null;
}
}
文件下载根据需要更改