Java文件Zip打包下载
/**
* 传入List,主要用于路径和文件名(文件名无要求的情况下可以直接以路径结尾进行下载)
*
* @param list 多个文件
* @param request
* @param response
* @throws Exception
*/
public void zipDownload(List<TcsHsfFile> list, HttpServletRequest request, HttpServletResponse response) throws Exception {
ZipOutputStream zos = null;
ServletOutputStream sos = null;
StorageServer storageServer = null;
byte[] b = null;
try {
response.reset();
// 通知客户文件的MIME类型:
response.setContentType("application/x-msdownload");
String filename = "default.zip";
response.setHeader("Content-disposition", "attachment;filename=" + filename);
sos = response.getOutputStream();
zos = new ZipOutputStream(sos);
ZipEntry ze = null;
int readLength = 0;
for (int i = 0; i < list.size(); i++) {
// 从list的得到路径和名称 list就是个包含路径的一个数组,大家可以修改他
String FilePath = list.get(i).getAddress();
String FileName = list.get(i).getFilename();
String conf = "classpath:conf" + File.separator + "clien.conf";
String downloadIp = DownloadIp(conf);
ClientGlobal.init(downloadIp);
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String substring = list.get(i).getAddress().substring(0, 6);
String substring2 = list.get(i).getAddress().substring(7);
b = storageClient.download_file(substring, substring2);
URL url = new URL("http://172.16.201.15/" + FilePath);
// 创建url连接;
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
// 链接远程服务器;
urlconn.connect();
ze = new ZipEntry(FileName);
ze.setSize(FilePath.length());
zos.putNextEntry(ze);
BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());
while ((readLength = bis.read(b, 0, 2048)) != -1) {
zos.write(b, 0, readLength);
}
bis.close();
}
} catch (Exception ex) {
logger.error("Error zipDownload:" + ex.toString());
} finally {
if (zos != null) {
try {
zos.close();
} catch (Exception ex) {
logger.error("Error zipDownload:" + ex.toString());
}
}
}
}