关于本地文件zip打包返回给浏览器下载,这边有个很好的例子读取本地文件打包返回给浏览器下载,基本能解决的相关问题。而最近因为项目原因,打包返回给浏览器下载的是存储在fdfs上文件,然后对此代码修改了下,解决了项目需求。所以就记录下,以便后续使用。
public void getAllFile(HttpServletResponse response,String callId) throws IOException{
String zipName = "file.zip";
//获取符合下载条件的实体列表,根据自己的需求定义
List<FileBean> fileList = getFileList(callId);
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename="+zipName);
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
try {
for(FileBean fileBean: fileList){
if(null==fileBean){
continue;
}
//只改变了以下这个方法即可
ZipUtils.doZip(fileBean.getFilePath(),fileBean.getFileName(), out);
response.flushBuffer();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
}
}
这边就ZipUtils工具类里的doZip()方法略微改变了下,如下:
public static void doZip(String inFile, String entryName,ZipOutputStream out)
throws IOException {
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
// String entryName = null;
// if (!"".equals(dir)) {
// entryName = dir + "/" + inFile.getName();
// } else {
// entryName = inFile.getName();
// }
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
int len = 0;
byte[] buffer = new byte[1024];
// FileInputStream fis = new FileInputStream(inFile);
// BufferedOutputStream bos = null;
urlfile = new URL(inFile);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
try {
bis = new BufferedInputStream(httpUrl.getInputStream());
} catch (FileNotFoundException f1) {
return;
}
while ((len = bis.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
out.closeEntry();
bis.close();
httpUrl.disconnect();
}
即可正确实现多文件打包下载。当然,与此类同,其他相似的存储系统文件打包下载,也可如此操作,进行打包下载,