前言
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。
这是给大家介绍的java 根据Url把多文件打包成ZIP下载,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我的支持!
一.代码示例**
// 根据url下载文件打包zip
private void getZip(HttpServletResponse response, String dbUrl)throws Exception{
//处理文件
String[] dbUrls = dbUrl.split(",");
String zipName = new Date().getTime() + ".zip";
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + zipName);
response.setCharacterEncoding("utf-8");
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
for (String iUrl : dbUrls) {
URL url = new URL(iUrl);// 读取url信息
zipOut.putNextEntry(new ZipEntry(FilenameUtils.getName(iUrl)));// 创建url文件
InputStream in = new BufferedInputStream(url.openStream());// 读取url文件信息
zipOut.write(readInputStream(in));//把url文件写入zip中
zipOut.closeEntry();// 关闭入口
in.close(); // 关闭连接
}
} catch (IOException e) {
throw new Exception("导出压缩包失败");
}
try {
// 声明一个工作薄 创建新的文件
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("ERROR:Download failed" + e.getMessage());
}
}
//根据文件链接把文件下载下来并且转成字节码
public byte[] readInputStream(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
try {
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
baos.flush();
} catch (Exception e) {
e.printStackTrace();
}
byte[] data = baos.toByteArray();
try {
is.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
二、url传值通过,隔开