直接附上工具類供參考
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SOhdTY0ATY1UTMxkTOzYTMmdTYxkzNxkjY4MDMhdDN48CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
友善複制,粘出代碼
-------------------------------------------------------------------------------------------
package maocco.smarts.facial.common;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import maocco.smarts.facial.entity.Facial;
public class PhotoZip {
//imgUrls 圖檔位址的集合
public static void downloadPic(List imgUrls,HttpServletRequest request,HttpServletResponse response) throws Exception {
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
try {
String downloadFilename = "壓縮封包件的名稱.zip";// 檔案的名稱
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 轉換中文否則可能會産生亂碼
response.setContentType("application/octet-stream");// 指明response的傳回對象是檔案流
response.setHeader("Content-Disposition","attachment;filename="+downloadFilename);// 設定在下載下傳框預設顯示的檔案名
String[] files = new String[imgUrls.size()];
imgUrls.toArray(files);
for (int i = 0; i < files.length; i++) {
String url = files[i];
zos.putNextEntry(new ZipEntry("download" + File.separator+i+ ".jpg"));
InputStream fis = getInputStreamByGet(url);
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
zos.flush();
zos.close();
}
}
public static 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;
}
}
-------------------------------------------------------------------------------------------
個人筆記,僅供參考
原文:https://www.cnblogs.com/1427wsl/p/12176583.html