SpringBoot 文件打包zip,浏览器下载出去
本地文件打包
/**
* 下载压缩包
*
* @param response
*/
@ResponseBody
@GetMapping("/downloadZip")
public void downloadZip(HttpServletResponse response,
// @RequestBody AssetInfoDownloadZipParam zipParam,
@RequestParam("agreementsIdList") List<Long> agreementsIdList, @RequestParam("attachmentsIdList") List<Long> attachmentsIdList) {
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<AssetInfoAgreements> assetInfoAgreementsList = assetInfoService.getAgreementsListByIds(agreementsIdList);
for (AssetInfoAgreements agreements : assetInfoAgreementsList) {
if (StringUtils.isNotBlank(agreements.getFilePath())) {
// Users/chenyanbin/Desktop/2023/05/11/test付款审批表____3LGPAc.pdf
String fileName = agreements.getFilePath();
File file = new File(fileName);
//判断文件是否存在
if (file.exists()) {
//将文件重命名
zos.putNextEntry(new ZipEntry("资产附件" + File.separator + file.getName().substring(0, file.getName().indexOf("____")) + file.getName().substring(file.getName().indexOf("."), file.getName().length())));
FileInputStream fis = new FileInputStream(file);
//使用字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(fis);
int len;
while ((len = bis.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
bis.close();
}
}
}
//资产文件列表
List<AssetInfoAttachments> attachmentsList = assetInfoService.getAttachmentsListByIds(attachmentsIdList);
for (AssetInfoAttachments attachments : attachmentsList) {
if (StringUtils.isNotBlank(attachments.getFilePath())) {
String fileName = attachments.getFilePath();
File file = new File(fileName);
//判断文件是否存在
if (file.exists()) {
zos.putNextEntry(new ZipEntry("资产文件" + File.separator + file.getName().substring(0, file.getName().indexOf("____")) + file.getName().substring(file.getName().indexOf("."), file.getName().length())));
FileInputStream fis = new FileInputStream(file);
//使用字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(fis);
int len;
while ((len = bis.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
bis.close();
}
}
}
// 没有文件,不需要文件的copy
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,浏览器下载出去的更多相关文章
- java 多个文件打包zip
/** * 多个文件打包成zip */ public class ZipDemo { private static void create() throws Exception{ String pat ...
- SpringBoot 文件上传、下载、设置大小
本文使用SpringBoot的版本为2.0.3.RELEASE 1.上传单个文件 ①html对应的提交表单 <form action="uploadFile" method= ...
- Web端文件打包.zip下载
使用ant.jar包的API进行文件夹打包.直接上代码: String zipfilename = "test.zip"; File zipfile = new File(zipf ...
- PHP打包zip并下载
$file_template = FCPATH.'canddata/cand_picture.zip';//在此之前你的项目目录中必须新建一个空的zip包(必须存在) $downname = $car ...
- Springboot文件上传与下载
一.创建简单的springboot-web项目 二.文件上传属性配置 #默认支持文件上传 spring.http.multipart.enabled =true spring.http.multipa ...
- springboot 文件上传和下载
文件的上传和下载 1.文件上传 html页面代码如下 <form method="post" action="/file/upload1" enctype ...
- 使用PHP自带zlib函数 几行代码实现PHP文件打包下载zip
<?php //获取文件列表 function list_dir($dir){ $result = array(); if (is_dir($dir)){ $file_dir = scandir ...
- PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载 && Linux下的ZipArchive配置开启压缩 &&搞个鸡巴毛,写少了个‘/’号,浪费了一天
PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有 ...
- PHP 用 ZipArchive 打包指定文件到zip供用户下载
Ubuntu需安装zlib sudo apt-get install ruby sudo apt-get install zlib1g zlib1g.dev Windows需开启php_zip.d ...
- PHP 多文件打包下载 zip
<?php $zipname = './photo.zip'; //服务器根目录下有文件夹public,其中包含三个文件img1.jpg, img2.jpg, img3.jpg,将这三个文件打包 ...
随机推荐
- 🔥🔥🔥httpsok-v1.8.0 SSL证书自动续签就应该这么简单
httpsok-v1.8.0 SSL证书自动续签就应该这么简单 简介 一行命令,一分钟轻松搞定SSL证书自动续期 httpsok 是一个便捷的 HTTPS 证书自动续签工具,专为 Nginx 服务器设 ...
- Linux(三):Linux的目录及相关作用
使用 Linux,不仅限于学习各种命令,了解整个 Linux 文件系统的目录结构以及各个目录的功能同样至关重要.使用 Linux 时,通过命令行输入 ls -l / 可以看到,在 Linux 根目录( ...
- 说一下flex的属性
flex-grow项目的放大比例,默认为0,即如果存在剩余空间,也不放大. flex-shrink属性定义了项目的缩小比例,默认为1,即如果空间不足,该项目将缩小.负值对该属性无效. flex-bas ...
- 全面系统的AI学习路径,帮助普通人也能玩转AI
前言 现如今AI技术和应用的发展可谓是如火如荼,它们在各个领域都展现出了巨大的潜力和影响力.AI的出现对于我们这些普通人而言也是影响匪浅,比如说使用AI工具GPT来写文档查问题.使用AI辅助编程工具帮 ...
- 有隙可乘 - Android 序列化漏洞分析实战
作者:vivo 互联网大前端团队 - Ma Lian 本文主要描述了FileProvider,startAnyWhere实现,Parcel不对称漏洞以及这三者结合产生的漏洞利用实战,另外阐述了漏洞利用 ...
- 线程安全使用 HashMap 的四种技巧
这篇文章,我们聊聊线程安全使用 HashMap 的四种技巧. 1方法内部:每个线程使用单独的 HashMap 如下图,tomcat 接收到到请求后,依次调用控制器 Controller.服务层 Ser ...
- kubernets之pod的生命周期容器启动后钩子以及容器结束前钩子
一 先来介绍容器启动后钩子 1.1 容器启动后钩子,并不是容器启动之后才会执行的操作,而是在容器启动过程中,异步的和容器进行启动的一种钩子它有2种表现形式,包括我们后面提到的容器结束前钩子一样 在一 ...
- C# 炸弹人 winform版
实现这个游戏的基本功能包含几个对象:玩家,怪物,墙砖,炸弹,通关的门.玩家通过上下左右方向键移动,放置炸弹,被怪物杀死,被炸弹炸死.怪物随机方向移动,能杀死玩家.炸弹有爆炸功能,炸弹的火花长度.通过的 ...
- 详解Spring循环依赖
一. 什么是循环依赖 循环依赖,就是两个或则两个以上的bean互相依赖对方,最终形成闭环.比如"A对象依赖B对象,而B对象也依赖A对象",或者"A对象依赖B对象,B对象依 ...
- NET框架下如何使用PaddleOCRSharp
打开VSIDE,新建Windows窗体应用(.NET Framework)类型的项目,选择一个.NET框架,如.NET Framework 4.0,右键点击项目,选择属性>生成,目标平台设置成X ...