业务要求:打包下载线上图片
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;
}