java下载多个文件,可以先把多个文件打包压缩成 zip 文件,然后下载zip文件
代码如下:
/**
* 生成zip
* @param sourcePath 原文件夹路径
* @param zipPath 生成的zip路径
*/
public static void createZip(String sourcePath, String zipPath) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
writeZip(new File(sourcePath), "", zos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if(file.exists()){
if(file.isDirectory()){//处理文件夹
parentPath+=file.getName()+File.separator;
File [] files=file.listFiles();
for(File f:files){
writeZip(f, parentPath, zos);
}
}else{
FileInputStream fis=null;
DataInputStream dis=null;
try {
fis=new FileInputStream(file);
dis=new DataInputStream(new BufferedInputStream(fis));
ZipEntry ze = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(ze);
zos.setEncoding("GBK");
byte [] content=new byte[1024];
int len;
while((len=fis.read(content))!=-1){
zos.write(content,0,len);
zos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(dis!=null){
dis.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
调用方法:
.createZip(FilePath+fileNameAll, FilePath+fileNameAll+".zip");
接下来就是下载:
/**
* 下载公共方法
* @param response
* @param str 下载的文件名
*/
private void downFile(HttpServletResponse response, HttpServletRequest request,String str) {
try {
String FilePath = request.getSession().getServletContext().getRealPath(File.separator);
String path = FilePath + str;
File file = new File(path);
if (file.exists()) {
InputStream ins = new FileInputStream(path);
BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
OutputStream outs = response.getOutputStream();// 获取文件输出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 设置response内容的类型
response.setHeader(
"Content-disposition",
"attachment;filename="
+ URLEncoder.encode(str, "UTF-8"));// 设置头部信息
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 开始向网络传输文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 这里一定要调用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
} else {
}
} catch (IOException e) {
}
}