本地文件打包
@GetMapping("/downloadZip") public void downloadZip(HttpServletResponse response) throws IOException { try { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("资产信息.zip", "UTF-8")); ServletOutputStream os = response.getOutputStream(); ZipOutputStream zos = new ZipOutputStream(os); byte[] buf = new byte[1024 * 2]; //资产附件列表 List<String> assetInfoAgreementsList = new ArrayList<String>() {{ this.add("/Users/chenyanbin/Desktop/code/ABS/2023/04/13/test三方验收单.pdf"); this.add("/Users/chenyanbin/Desktop/code/ABS/2023/04/13/test付款审批表.pdf"); this.add("/Users/chenyanbin/Desktop/code/ABS/2023/04/13/test合同关键页.pdf"); this.add("/Users/chenyanbin/Desktop/1.pdf"); }}; for (String fileName : assetInfoAgreementsList) { File f = new File(fileName); //判断文件是否存在 if (f.exists()) { zos.putNextEntry(new ZipEntry("资产附件\\"+fileName.substring(fileName.lastIndexOf("/") + 1))); FileInputStream fis = new FileInputStream(f); //使用字节缓冲输入流 BufferedInputStream bis = new BufferedInputStream(fis); int len; while ((len = bis.read(buf)) != -1) { zos.write(buf, 0, len); } zos.closeEntry(); bis.close(); } } //资产文件列表 List<String> attachmentsList = new ArrayList<String>() {{ this.add("/Users/chenyanbin/Desktop/code/ABS/xxx平台资产服务接口.pdf"); this.add("/Users/chenyanbin/Desktop/1.jpg"); }}; for (String fileName : attachmentsList) { File f = new File(fileName); if (f.exists()) { zos.putNextEntry(new ZipEntry("资产文件\\" + fileName.substring(fileName.lastIndexOf("/") + 1))); FileInputStream fis = new FileInputStream(f); //使用字节缓冲输入流 BufferedInputStream bis = new BufferedInputStream(fis); int len; while ((len = bis.read(buf)) != -1) { zos.write(buf, 0, len); } zos.closeEntry(); bis.close(); } } zos.closeEntry(); //必须要执行 zos.finish(); close()时内部会调用finish() zos.close(); } catch (Exception e) { e.printStackTrace(); log.error("资产信息下载zip异常:{}", e); } }
远程url文件打包
工具类
package com.ybchen.utils; import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @ClassName ZipUtils * @Description zip工具类 * @Author Alex * @Date 2023/4/23 下午8:55 * @Version 1.0 */ @Slf4j public class ZipUtils { /** * 通过url下载zip * @param response 响应流 * @param urls url文件路径集合 * @param zipName xxx.zip */ public static void urlDownloadToZip(HttpServletResponse response, List<String> urls, String zipName) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); for (String oneFile : urls) { byte[] bytes = getFileFromURL(oneFile); zos.putNextEntry(new ZipEntry(parseFileName(oneFile))); zos.write(bytes, 0, bytes.length); zos.closeEntry(); } zos.close(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipName, "UTF-8")); OutputStream os = response.getOutputStream(); os.write(bos.toByteArray()); os.close(); } catch (FileNotFoundException ex) { log.error("FileNotFoundException", ex); } catch (Exception ex) { log.error("Exception", ex); } } private static Pattern pattern = Pattern.compile("\\S*[?]\\S*"); /* * 解析url的文件名称 */ private static String parseFileName(String url) { Matcher matcher = pattern.matcher(url); String[] spUrl = url.toString().split("/"); int len = spUrl.length; String endUrl = spUrl[len - 1]; if (matcher.find()) { String[] spEndUrl = endUrl.split("\\?"); return spEndUrl[0].split("\\.")[0] + "." + spEndUrl[0].split("\\.")[1]; } return endUrl.split("\\.")[0] + "." + endUrl.split("\\.")[1]; } /** * 根据文件链接把文件下载下来并且转成字节码 * * @param urlPath url路径 * @return */ public static byte[] getFileFromURL(String urlPath) { byte[] data = null; InputStream is = null; HttpURLConnection conn = null; try { URL url = new URL(urlPath); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // conn.setDoOutput(true); // conn.setRequestMethod("GET"); conn.setConnectTimeout(6000); is = conn.getInputStream(); if (conn.getResponseCode() == 200) { data = readInputStream(is); } else { data = null; } } catch (MalformedURLException e) { log.error("MalformedURLException", e); } catch (IOException e) { log.error("IOException", e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { log.error("IOException", e); } conn.disconnect(); } return data; } private static 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 (IOException e) { log.error("IOException", e); } byte[] data = baos.toByteArray(); try { is.close(); baos.close(); } catch (IOException e) { log.error("IOException", e); } return data; } }
调用
@GetMapping("/testDownloadZip") public void testDownloadZip(HttpServletResponse response) { try { List<String> urlList = new ArrayList<>(); urlList.add("https://chenyanbin.oss-cn-hangzhou.aliyuncs.com/20210103/1.png"); urlList.add("https://pic.cnblogs.com/face/1854114/20221126134321.png"); urlList.add("https://files.cnblogs.com/files/chenyanbin/redeploy-rancher2-workload.zip?t=1682071754&download=true"); ZipUtils.urlDownloadToZip(response, urlList, "测试.zip"); } catch (Exception e) { e.printStackTrace(); } }标签:浏览器,SpringBoot,zip,fileName,zos,import,new,response From: https://www.cnblogs.com/chenyanbin/p/17347823.html