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 ...
随机推荐
- python中random模块
random与numpy.random对比: 1.random.random():生成[0,1)之间的随机浮点数: numpy.random.random():生成[0,1)之间的随机浮点数: num ...
- Yii2后台管理系统常规单据模块最佳实践
后台管理系统的常规单据通常包括数据,页面,功能:其中数据,页面,功能又可以细分如下: 分类 二级分类 主要内容 注意事项 例如 数据 数据库迁移脚本 用于数据表生成及转态回滚 1.是否需要增 ...
- eclipse 基础快捷键。
批量修改:Alt+Shift+R 查看java源码:1.选中方法,比如System.out.println()的 println 2.F3 代码格式化:ctrl+shift+f (注意: 这个快捷键和 ...
- Nginx GoAccess安装与配置
1.下载并安装Geoip $ wget https://github.com/maxmind/geoip-api-c/releases/download/v1.6.12/GeoIP-1.6.12.ta ...
- 实现中英文混合string的逆向输出
#include <iostream> using namespace std; // 输入一个字符串(包括英文和中文),将其反序输出, 如: // hello 今天真热 ---> ...
- Lambda 动态表达式(排序)
网上看到的: class Program { static List<User> list = new List<User>() { new User(){ID=1,Name= ...
- Django+Vue打造购物网站(三)
商品列表页 通过商品列表页面来学习drf django的view实现商品列表页 在goods目录下新建一个views_base.py文件,用来区分drf的view和Dajngo自带的view的区别 利 ...
- 洛谷P1092 虫食算(算竞进阶习题)
模拟+dfs 这个题就三行,搜索的话我们从右向左,从上到下.. 如果是在1,2行我们就直接枚举0-n所有数,但是到了第三行,最直接的就是填上这一列上前两行的数的和modN,在此基础上判断该填的数有没有 ...
- Voltage Keepsake CodeForces - 801C (贪心 || 二分)
C. Voltage Keepsake time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- CF1106F Lunar New Year and a Recursive Sequence
题目链接:CF1106F Lunar New Year and a Recursive Sequence 大意:已知\(f_1,f_2,\cdots,f_{k-1}\)和\(b_1,b_2,\cdot ...