最近需要這個所以寫了一個例子
一般批量下載由以下步驟組成:
1、確定下載的源文件位置
2、對文件進行打包成臨時文件,這里會用到遞歸調用,需要的嵌套的文件夾進行處理,並返回文件保存位置
3、將打包好的文件下載
4、下載完成將打包的臨時文件刪除
下面的代碼中鑒於簡單方便,作為例子使用,使用純的jsp實現下載,沒有配置成servlet,
下載時使用JS事件模擬功能直接請求JSP文件方式,如果需要使用servlet方式,
可把jsp中的java代碼搬到servlet中
文件打包 zip 代碼:
package com.downloadZip;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class DownloadZip {
private static int BUF_SIZE = 1024*10;
public static void main(String[] args) {
try {
File f = new DownloadZip().createZip("D:/img","D:/imgs","img");
System.out.println(f.getPath());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 創建壓縮文件
* @param sourcePath 要壓縮的文件
* @param zipFilePath 文件存放路徑
* @param zipfileName 壓縮文件名稱
* @return File
* @throws IOException
*/
public File createZip(String sourcePath ,String zipFilePath,String zipfileName) throws IOException{
//打包文件名稱
zipfileName = zipfileName+".zip";
/**在服務器端創建打包下載的臨時文件夾*/
File zipFiletmp = new File(zipFilePath+"/tmp"+System.currentTimeMillis());
if(!zipFiletmp.exists() && !(zipFiletmp.isDirectory())){
zipFiletmp.mkdirs();
}
File fileName = new File(zipFiletmp,zipfileName);
//打包文件
createZip(sourcePath,fileName);
return fileName;
}
/**
* 創建ZIP文件
* @param sourcePath 文件或文件夾路徑
* @param zipPath 生成的zip文件存在路徑(包括文件名)
*/
public void createZip(String sourcePath, File zipFile) {
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile),BUF_SIZE));
writeZip(new File(sourcePath), "", zos);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* 創建ZIP文件
* @param sourcePath 文件或文件夾路徑
* @param zipPath 生成的zip文件存在路徑(包括文件名)
*/
public void createZip(String sourcePath, String zipPath) {
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath),BUF_SIZE));
writeZip(new File(sourcePath), "", zos);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
*
* @param file
* @param parentPath
* @param zos
*/
private 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{
DataInputStream dis=null;
try {
dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
ZipEntry ze = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(ze);
byte [] content=new byte[BUF_SIZE];
int len;
while((len=dis.read(content))!=-1){
zos.write(content,0,len);
zos.flush();
}
zos.closeEntry();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally{
try {
if(dis!=null){
dis.close();
}
}catch(IOException e){
throw new RuntimeException(e);
}
}
}
}
}
/**
* 刪除文件
* @param file
* @return
* @throws Exception
*/
public boolean delFile(File file) throws Exception {
boolean result = false;
if(file.exists()&&file.isFile())
{
file.delete();
file.getParentFile().delete();
result = true;
}
return result;
}
}
JSP 下載邏輯代碼:
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ page import="java.net.*"%>
<%@ page import="java.io.*"%>
<%@ page import="com.downloadZip.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>
</head>
<body>
<%
// 創建壓縮包並返回壓縮包位置
DownloadZip downloadZip = new DownloadZip();
File zipfile = downloadZip.createZip("D:/img","D:/imgs","img");
String path=zipfile.getPath();
// 獲取文件名
String fileName=path.substring(path.lastIndexOf("\\")+1);
System.out.println(fileName);
//制定瀏覽器頭
//如果圖片名稱是中文需要設置轉碼
response.setCharacterEncoding("GBK");
response.setContentType("application/x-download");//設置為下載application/x-download
response.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "GBK"));
InputStream reader = null;
OutputStream outp = null;
byte[] bytes = new byte[1024];
int len = 0;
try {
// 讀取文件
reader = new FileInputStream(path);
// 寫入瀏覽器的輸出流
outp = response.getOutputStream();
while ((len = reader.read(bytes)) > 0) {
outp.write(bytes, 0, len);
outp.flush();
}
out.clear();
out = pageContext.pushBody();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
//這里貌似不能關閉,如果關閉在同一個頁面多次點擊下載,會報錯
//if (outp != null)
// outp.close();
downloadZip.delFile(zipfile);
}
%>
</body>
</html>
最終效果:
設置下載目錄,讓文件下載至規定的目錄:C:\Users\liu\Desktop\工程項目
開始批量下載文件:
文件已完成批量下載,去文件目錄中看看:
文件已在目錄中了,很方便。
詳細配置信息可以參考我寫的這篇文章: http://blog.ncmem.com/wordpress/2019/08/28/net%e6%96%87%e4%bb%b6%e6%89%b9%e9%87%8f%e4%b8%8b%e8%bd%bd/