Java 多个文件压缩下载
有时候会有多个附件一起下载的需求,这个时候最好就是打包下载了
首先下面这段代码是正常的单个下载
public void Download(@RequestParam("file_path") String file_path, HttpServletResponse response) {
logger.info("try to download file, the filePath : " + file_path);
int i = file_path.lastIndexOf("/");
String filename = file_path.substring(i+1);
try {
BufferedInputStream in=new BufferedInputStream(ossFileUtil.getFile(file_path));
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
//通知浏览器以附件形式下载
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
byte[] car=new byte[1024];
int L=0;
while((L=in.read(car))!=-1){
out.write(car, 0,L);
}
if(out!=null){
out.flush();
out.close();
}
if(in!=null){
in.close();
}
} catch (IOException e) {
logger.error("the download file error :" + e.getMessage());
throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
}
}
下面代码是打包下载
public void serverDownloads(@RequestParam("file_path") String file_path,
@RequestParam(name = "download_name", required = false) String download_name,
HttpServletResponse response) throws IOException {
logger.info("try to download server file, the filePath : " + file_path);
String[] paths = file_path.split(",\\$\\$,");
if(paths.length > 1){
// 打包的文件名
String packageName;
if (download_name != null && download_name.trim().length() > 0) {
packageName = download_name + ".zip";
} else {
packageName = "file.zip";
}
//打包下载
response.setContentType("APPLICATION/OCTET-STREAM");
// response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(packageName,"utf-8"));
response.setHeader("Content-Disposition","attachment;filename=" + packageName);
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
try {
int j = 1;
for(String path : paths){
int i = path.lastIndexOf("/");
String filename = path.substring(i+1);
ZipUtils.doZip(remoteFileUtil.getFile(path), out, filename);
response.flushBuffer();
j++;
}
} catch (IOException e) {
logger.error("the download file error :" + e.getMessage());
throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
}finally{
out.close();
}
}else{
int i = file_path.lastIndexOf("/");
String filename = file_path.substring(i+1);
try {
BufferedInputStream in=new BufferedInputStream(remoteFileUtil.getFile(file_path)); //BufferedInputStream(InputStream in)
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
//通知浏览器以附件形式下载
// response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
response.setHeader("Content-Disposition","attachment;filename=" + filename);
byte[] car=new byte[1024];
int L=0;
while((L=in.read(car))!=-1){
out.write(car, 0,L);
}
if(out!=null){
out.flush();
out.close();
}
if(in!=null){
in.close();
}
} catch (IOException e) {
logger.error("the download file error :" + e.getMessage());
throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
}
}
}
最后是ZipUtils类内容
public class ZipUtils {
private ZipUtils(){
}
public static void doCompress(String srcFile, String zipFile) throws IOException {
doCompress(new File(srcFile), new File(zipFile));
}
/**
* 文件压缩
* @param srcFile 目录或者单个文件
* @param zipFile 压缩后的ZIP文件
*/
public static void doCompress(File srcFile, File zipFile) throws IOException {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(zipFile));
doCompress(srcFile, out);
} catch (Exception e) {
throw e;
} finally {
out.close();//记得关闭资源
}
}
public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
doCompress(new File(filelName), out);
}
public static void doCompress(File file, ZipOutputStream out) throws IOException{
doCompress(file, out, "");
}
public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
if ( inFile.isDirectory() ) {
File[] files = inFile.listFiles();
if (files!=null && files.length>0) {
for (File file : files) {
String name = inFile.getName();
if (!"".equals(dir)) {
name = dir + "/" + name;
}
ZipUtils.doCompress(file, out, name);
}
}
} else {
ZipUtils.doZip(inFile, out, dir);
}
}
public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
String entryName = null;
if (!"".equals(dir)) {
entryName = dir + "/" + inFile.getName();
} else {
entryName = inFile.getName();
}
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
int len = 0 ;
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(inFile);
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
out.closeEntry();
fis.close();
}
//
public static void doZip(InputStream inputStream, ZipOutputStream out, String entryName) throws IOException {
// String entryName = null;
// if (!"".equals(dir)) {
// entryName = dir + "/" + inFile.getName();
// } else {
// entryName = inFile.getName();
// }
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
int len = 0 ;
byte[] buffer = new byte[1024];
// FileInputStream fis = new FileInputStream(inFile);
while ((len = inputStream.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
out.closeEntry();
inputStream.close();
}
public static void main(String[] args) throws IOException {
doCompress("G:/test/", "G:/java.zip");
}
}
Java 多个文件压缩下载的更多相关文章
- java多个文件压缩下载
public static void zipFiles(File[] srcfile,ServletOutputStream sos){ byte[] buf=new byte[1024]; try ...
- Java /C# 实现文件压缩
纯粹为了记录. 参考了 https://www.cnblogs.com/zeng1994/p/7862288.html import java.util.List; import java.util. ...
- java实现将文件压缩成zip格式
以下是将文件压缩成zip格式的工具类(复制后可以直接使用): zip4j.jar包下载地址:http://www.lingala.net/zip4j/download.php package util ...
- php多文件压缩下载
/*php多文件压缩并且下载*/ function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定. whil ...
- 利用Java进行zip文件压缩与解压缩
摘自: https://www.cnblogs.com/alphajuns/p/12442315.html 工具类: package com.alphajuns.util; import java.i ...
- asp.net mvc 文件压缩下载
压缩文件相关的类: public class ZIPCompressUtil { public static Tuple<bool, Stream> Zip(string strZipTo ...
- Java实现多文件压缩打包的方法
package com.biao.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutpu ...
- java代码实现文件的下载功能
昨天,根据需求文档的要求,自己要做一个关于文件下载的功能,从学校毕业已经很久了,自己好长时间都没有做过这个了,于是自己上网百度,最终开发出来的代码如下: 哦!对了,我先说一下我的思路,首先需要获取服务 ...
- ftp多文件压缩下载
@GetMapping(value = "/find") public String findfile(String filePath, String fileNames, Htt ...
随机推荐
- HTML5经典案例学习-----新元素添加文档结构
直接上代码了,大家如果发现问题了,记得提醒我哦,谢谢啦,嘻嘻 <!DOCTYPE html> <!-- 不区分大小写 --> <html lang="en&qu ...
- java学习之—递归实现变位字
/** * 递归实现变位字 * Create by Administrator * 2018/6/20 0020 * 上午 10:23 **/ public class AnagramApp { st ...
- Js--动态生成表格
<div> <h1>动态生成表格</h1> <div id="table1"> 行 ...
- mysql分页查询按某类型置顶 按某类型置尾 再按优先级排序
近段时间接到一个新需求: 第一优先级:未满的标的顺位高于已满标的顺位.第二优先级:新手标的顺位高于其他标的的顺位. 第三优先级:标的剩余可投金额少的顺位高于标的剩余可投金额多的. 我是直接通过sql语 ...
- Windows 访问 CentOS 7 共享文件夹 Samba 配置
Windows 使用用户名.密码访问 CentOS 7 共享文件夹 执行命令,查看 Windows 工作组:net config workstation 执行命令,安装 Samba:yum insta ...
- iOS 根据时间戳计算聊天列表的时间(上午/下午)
把时间戳转成聊天时间(上午 10:00 . 昨天 14:00 . 3月15日 15:00) +(NSString*)ChatingTime:(NSString *)timestring{ int ...
- Spring 使用介绍(四)—— SpEL
一.SpEL介绍 Spring表达式语言全称为“Spring Expression Language”,缩写为“SpEL”,可在运行时构建复杂表达式 使用步骤: 1)创建解析器:ExpressionP ...
- Git——取消merge状态
MERGING状态 取消MERGING 查看更新历史 $ git reflog 恢复之前状态 $ git reset --hard 06a5578
- 微信小程序——安装开发工具和环境【二】
准备 开发工具下载 获取APPID 安装工具 安装 接受协议 选择安装位置 等待安装完成 安装完成 选择项目 选择小程序 填写信息 确定 无误后,点击确定进入开发页面 建立普通快速启动模板界面
- Codeforces1065G Fibonacci Suffix 【递推】【二分答案】
题目分析: 首先为了简便起见我们把前$15$的答案找出来,免得我们还要特判$200$以内之类的麻烦事. 然后我们从$16$开始递推.考虑猜测第i位是$0$还是$1$(这本质上是个二分).一开始先猜是$ ...