JAVA 线上图片压缩下载

业务要求:打包下载线上图片

service层

public void downImgZip(List<String> paths, HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		// List<String> paths 需要压缩的图片地址
		//注意编码格式
		String downloadName = new String(("下载压缩包名称" + ".zip").getBytes("UTF-8"),
				"ISO-8859-1");
		//响应头的设置
		response.reset();
		response.setCharacterEncoding("utf-8");
//		response.setContentType("multipart/form-data");
		response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
		response.setHeader("Content-Disposition", "attachment;filename=" + downloadName);// 设置在下载框默认显示的文件名
		// 设置压缩流:直接写入response,实现边压缩边下载
		ZipOutputStream zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
		zipos.setMethod(ZipOutputStream.DEFLATED); // 设置压缩方法
		// 循环将文件写入压缩流
		DataOutputStream os = null;
		for (String url : paths) {
			//文件名
			String filename =url.substring(0, url.indexOf("*"));
			//图片地址
			String path=url.substring(filename.length()+1, url.length());
			// 添加ZipEntry,并ZipEntry中写入文件流
			zipos.putNextEntry(new ZipEntry(filename+ ".jpg"));
			os = new DataOutputStream(zipos);
			InputStream is = getInputStreamByGet(path);
			byte[] b = new byte[1024];
			int length = 0;
			while ((length = is.read(b)) != -1) {
				os.write(b, 0, length);
			}
			is.close();
			zipos.closeEntry();
		}
		os.flush();
		os.close();
		zipos.flush();
		zipos.close();
	}

	// 通过get请求得到读取器响应数据的数据流
	public InputStream getInputStreamByGet(String url) {
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setReadTimeout(5000);
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream inputStream = conn.getInputStream();
				return inputStream;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值