您好,登錄后才能下訂單哦!
本篇內容主要講解“Java怎么下載壓縮包”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Java怎么下載壓縮包”吧!
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, List<String> fileUrl, 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<String> 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怎么下載壓縮包”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。