Java文件Zip打包下载

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());
				}
			}
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值