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 ...
随机推荐
- js如何复制一个对象?
方法一: 把原来对象的属性遍历一遍,赋给一个新的对象. //深复制对象方法 var cloneObj = function (obj) { var newObj = {}; if (obj insta ...
- 【纪录】Hash about
backup a easy implement # coding: utf-8 def add(k, v): pass def get(target): pass class LinearMap(ob ...
- 结巴(jieba)分词
一.介绍: jieba: “结巴”中文分词:做最好的 Python 中文分词组件 “Jieba” (Chinese for “to stutter”) Chinese text segmentatio ...
- /dev被异常删除的问题
今天遇到一个问题,在执行某些操作后,发现经常报“read_urandom: /dev/urandom: open failed: No such file or directory”这个错误.后来查看 ...
- DAY07、字符编码和文件操作
一.字符编码 1.什么是字符编码? 人类能识别的是字符等高级标识符,电脑只能识别0,1组成的标识符,要完成人与机器之间的信息交流, 一定需要一个媒介,进行两种标识符的转化(两 ...
- 莫烦theano学习自修第五天【定义神经层】
1. 代码如下: #!/usr/bin/env python #! _*_ coding:UTF-8 _*_ import numpy as np import theano.tensor as T ...
- python数据结构算法学习自修第一天【数据结构与算法引入】
1.算法引入: #!/usr/bin/env python #! _*_ coding:UTF-8 _*_ from Queue import Queue import time que = Queu ...
- WEB相关概念、Tomcat初识、Servlet、基本知识。
/* * 一.web的概念? * 1.web就是在http协议基础之上, 利用浏览器进行访问的网站. * Web Page指网站内的网页. 我们常说的WWW(World Wide Web 万维网)就是 ...
- js函数使用prototype和不适用prototype的区别
js中类定义函数时用prototype与不用的区别 原创 2017年06月05日 12:25:41 标签: 函数 / prototype / class 首先来看一个实例: function Li ...
- webpack配置之代码优化
前面的话 前面介绍了webpack的基本配置,本文将详细介绍webpack中关于代码优化的配置 打包公共代码 CommonsChunkPlugin 插件,是一个可选的用于建立一个独立文件(又称作 ch ...