/**
* 给定一组url,将此集合地址下对应的资源下载到浏览器
*
* @param urls url地址的集合
* @throws IOException
*/
public static void downloadPic(List<String> urls, 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;charset=UTF-8");// 指明response的返回对象是文件流
response.setHeader("Content-Disposition","attachment;filename="+downloadFilename);// 设置在下载框默认显示的文件名
for (String url : urls) {
String imgName = LocalDateTime.now().toString();
String suffix = url.substring(url.lastIndexOf("."));
zos.putNextEntry(new ZipEntry(imgName + suffix));
InputStream fis = getInputStreamByGet(url);
byte[] bytes = new byte[1024];
int len;
while (true) {
assert fis != null;
if ((len = fis.read(bytes)) == -1) break;
zos.write(bytes, 0, len);
}
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) {
return conn.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
java实现根据url批量下载图片到浏览器
最新推荐文章于 2025-06-29 11:45:48 发布