批量下载文件web
最近需要这个所以写了一个例子
一般批量下载由以下步骤组成:
2、对文件进行打包成临时文件,这里会用到递归调用,需要的嵌套的文件夹进行处理,并返回文件保存位置
4、下载完成将打包的临时文件删除
文件打包 zip 代码:
} 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 下载逻辑代码:
最终效果:
设置下载目录,让文件下载至规定的目录:C:\Users\liu\Desktop\工程项目
文件已完成批量下载,去文件目录中看看:
文件已在目录中了,很方便。