List<String> files = new ArrayList<String>(); //图片地址集合
String downloadFilename = System.currentTimeMillis()+".zip";//文件的名称
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
int i = 0;
for (String string : files) {
URL url = new URL(string);
HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
String message = urlcon.getHeaderField(0);
if(StringUtils.isNotEmpty(message)){
if (message.startsWith("HTTP/1.1 404")) {
continue;
}
zos.putNextEntry(new ZipEntry((++i)+".jpg"));
InputStream fis = urlcon.getInputStream();
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
}
zos.flush();
zos.close();
java批量打包下载网络图片
最新推荐文章于 2022-09-13 15:04:08 发布