有时候会有多个附件一起下载的需求,这个时候最好就是打包下载了

首先下面这段代码是正常的单个下载

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 多个文件压缩下载的更多相关文章

  1. java多个文件压缩下载

    public static void zipFiles(File[] srcfile,ServletOutputStream sos){ byte[] buf=new byte[1024]; try ...

  2. Java /C# 实现文件压缩

    纯粹为了记录. 参考了 https://www.cnblogs.com/zeng1994/p/7862288.html import java.util.List; import java.util. ...

  3. java实现将文件压缩成zip格式

    以下是将文件压缩成zip格式的工具类(复制后可以直接使用): zip4j.jar包下载地址:http://www.lingala.net/zip4j/download.php package util ...

  4. php多文件压缩下载

    /*php多文件压缩并且下载*/ function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定. whil ...

  5. 利用Java进行zip文件压缩与解压缩

    摘自: https://www.cnblogs.com/alphajuns/p/12442315.html 工具类: package com.alphajuns.util; import java.i ...

  6. asp.net mvc 文件压缩下载

    压缩文件相关的类: public class ZIPCompressUtil { public static Tuple<bool, Stream> Zip(string strZipTo ...

  7. Java实现多文件压缩打包的方法

    package com.biao.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutpu ...

  8. java代码实现文件的下载功能

    昨天,根据需求文档的要求,自己要做一个关于文件下载的功能,从学校毕业已经很久了,自己好长时间都没有做过这个了,于是自己上网百度,最终开发出来的代码如下: 哦!对了,我先说一下我的思路,首先需要获取服务 ...

  9. ftp多文件压缩下载

    @GetMapping(value = "/find") public String findfile(String filePath, String fileNames, Htt ...

随机推荐

  1. 剑指offer(5)

    题目: 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 解法: 一个栈专门用来存数,当需要输出数时,把所有数倒到第二个栈,当然,若此时第二个栈中已经有数了(之前倒 ...

  2. cookie,localStorage和sessionStorage区别

    三者的异同 特性 Cookie localStorage sessionStorage 数据的生命期 一般由服务器生成,可设置失效时间.如果在浏览器端生成Cookie,默认是关闭浏览器后失效 除非被清 ...

  3. JAVA不可变类(immutable)机制与String的不可变性--非常好.

    JAVA不可变类(immutable)机制与String的不可变性 https://www.cnblogs.com/jaylon/p/5721571.html

  4. Linux下 rewrite_mod 的配置

    以下使用最新的 Ubuntu 16.04 测试; 安装好apache后先确认有没有rewrite模块,大多数情况下是有的:ls /etc/apache2/mods-available |grep re ...

  5. Winform实现多线程异步更新UI(进度及状态信息)

    引言 在进行Winform程序开发需要进行大量的数据的读写操作的时候,往往会需要一定的时间,然在这个时间段里面,界面ui得不到更新,导致在用户看来界面处于假死的状态,造成了不好的用户体验.所以在大量数 ...

  6. How to install rime on Debian

    apt-get install ibus ibus-rime librime-data-wubi reboot cp ~/.config/ibus/rime/default.yaml ~/.confi ...

  7. react用构造函数创建组件

    有两种方法,一种是通过构造函数创建,一种是通过class创建 1.构造函数创建组件 用function+组件名的方式创建,创建好了,在render里面以标签的形式一丢就可以啦!但是这种方式必须要ret ...

  8. THEPYTHONCHALLENG闯关记录

    由于是自己看视频学python,总觉得不写几行代码就什么都没有学到. 找了一个写代码的网站其实只是因为这个看起来好玩. 闯关地址http://www.pythonchallenge.com/index ...

  9. 向继电器发送socket请求(python+java)

    近日,有一需求,向连接在内网的继电器发送socket请求,加以控制.原本并不复杂,只是io流/socket转换的问题,实操中却出现python代码没问题,java代码执行无响应的问题,问题很好定位:没 ...

  10. Go语言函数相关

    1.函数的声明定义 //func关键字 //getStudent函数名 //(id int, classId int) 参数列表 //(name string,age int) 返回值列表 func ...