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 ...
随机推荐
- 解决方法:CentOS7用yum安装软件显示错误:cannot find a valid baseurl for repo: base/7/x86_64
在Linux学习中,发现使用yum安装软件出现以下的错误: 百度了各种方法,很多人也发现光是修改REBOOT=yes也没用,多次进行挂载.修改网卡配置文件.重置IP地址.重启网络.创建又删除配置文件的 ...
- idea 创建的spingmvc 引入jquery后jquery函数始终不执行的原因
- Spark join连接
内链接
- Linux用户权限指令, 定时任务等指令
一. 网卡配置详解 网络配置文件: /etc/sysconfig/network 网络接口配置文件: /etc/sysconfig/network-scripts/ifcfg-INTERFACE_NA ...
- ssm框架整合配置,用maven配置依赖jar包
1.创建maven project 首先在pom.xml中指定工程所依赖的jar包 <project xmlns="http://maven.apache.org/POM/4.0.0& ...
- python3 阿里云控制SLB权重
一.配置好RAM账号的权限(SLB管理权限) 二.安装依赖 pip3 install aliyun-python-sdk-slb pip3 install aliyun-python-sdk-core ...
- awk骚操作
一.awk自加 [root@168web3 ~]# head /data/logs/cloud_monitor_rds_cpu.log |awk '{sum+=$NF}END{print sum}' ...
- 01.javascript之数据类型
1.数据类型 JavaScript一共有六种数据类型.(ES6新增了第七种Symbol类型的值) 数值(Number) 字符串(String) 布尔值(boolean) undefined null ...
- Y7000联想拯救者gtx1050Ti安装cuda9.0
安装cuda经常会遇到安装失败的问题,原因大部分都是由于驱动不一致引起的,接下来我们分两步讲解 1. 安装驱动失败 原因:nvidia官网提供的驱动都是通用的,针对特殊设备可能出现不兼容问题,方法很简 ...
- codeforces509B
Painting Pebbles CodeForces - 509B There are n piles of pebbles on the table, the i-th pile contains ...