java打包下载文件,需要使用apache的ant.jar,代码如下:
public void exportAllQrCode(HttpServletRequest request,HttpServletResponse response){
List<StoreInformation> storeList = storeInformationService.getAllByList();
String urlStr = "";
try {
String fileName = "aa.zip";
File f = new File(request.getRealPath("")+"/temp");
if(!f.exists()){
f.mkdir();
}
String outFilePath = request.getRealPath("")+"/temp/"+fileName;
File file = new File(outFilePath);
ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[1024];
DataInputStream dataInputStream = null;
String siid = "";
String siname = "";
if(storeList!=null && storeList.size()>0){
for(int i=0;i<storeList.size();i++){
siid = storeList.get(i).getSiid();
siname = storeList.get(i).getSiname();
urlStr = Utils.getBasePath(request)+"/code/pic/"+siid+".jpg";
URL url = new URL(urlStr);
dataInputStream = new DataInputStream(url.openStream());
zipout.setEncoding("GBK");
zipout.putNextEntry(new ZipEntry(siname+".jpg"));
int len = 0;
while((len=dataInputStream.read(buffer))>0){
zipout.write(buffer, 0, len);
}
zipout.closeEntry();
dataInputStream.close();
}
}
zipout.close();
LOGGER.info("***********zip文件生成成功*********");
//******URL中带中文****//
urlStr = Utils.getBasePath(request)+"/temp/"+fileName;
URL url = new URL(urlStr);
DataInputStream ds = new DataInputStream(url.openStream());
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int length = 0;
while((length=ds.read(buffer))!=-1){
out.write(buffer, 0, length);
out.flush();
}
ds.close();
out.close();
file.delete();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e){
e.printStackTrace();
throw new RuntimeException("生成压缩包时,源文件不存在:"+urlStr, e);
} catch (IOException e) {
e.printStackTrace();
}
}