Java怎么下载压缩包
本篇内容主要讲解“Java怎么下载压缩包”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java怎么下载压缩包”吧!
专注于为中小企业提供做网站、成都做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业惠济免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了1000多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
package com.golden.crm.web.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * 下载zip工具类 */ public class ZipUtil { private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class); /** * 生成Zip文件 */ public static void generateZipFile(HttpServletResponse response, ListfileUrl, String fileName) throws IOException { ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream()); for (int i = 0; i < fileUrl.size(); i++) { zipOut.putNextEntry(new ZipEntry(System.currentTimeMillis() + ".jpg")); InputStream stream = this.getInputStreamByUrl(fileUrl.get(i)); if (null == stream) { continue; } int temp = 0; while ((temp = stream.read()) != -1) { zipOut.write(temp); } stream.close(); } zipOut.closeEntry(); zipOut.close(); } /** * 通过url读取图片信息 */ public static InputStream getInputStreamByUrl(String url) { InputStream ins = null; try { URL url_ = new URL(url); HttpURLConnection conn = (HttpURLConnection) url_.openConnection(); conn.setConnectTimeout(3 * 1000); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); ins = conn.getInputStream(); } catch (IOException e) { logger.info("图片读取失败!-->" + e); } return ins; } /** * 导出Zip文件 */ public static void exportZipFile(String fileName, List fileUrl, HttpServletResponse response, HttpServletRequest request) { try { // 浏览器处理乱码问题 String userAgent = request.getHeader("User-Agent"); // filename.getBytes("UTF-8")处理safari的乱码问题 byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // 各浏览器基本都支持ISO编码 fileName = new String(bytes, "ISO-8859-1"); // 文件名外的双引号处理firefox的空格截断问题 response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName)); response.setContentType("application/x-msdownload"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); this.generateZipFile(response, fileUrl, fileName); } catch (Exception e) { logger.info("下载失败!-->" + e); } } }
到此,相信大家对“Java怎么下载压缩包”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
当前文章:Java怎么下载压缩包
当前URL:http://pwwzsj.com/article/ihedsj.html