类:
/**
* <br>入口参数:path,filenames
* <br>出口参数:String
* <br>功能介绍:从数据库读取EXCEL文件路径(不包含文件名),名称,压缩成一个zip文件
* @return Zip文件保存路径
*/
public String getZipFilepath(String path, ArrayList filenames) throws
Exception {
String zipurl = path + "Excel.zip";
String dir = path;
ArrayList fileNames = filenames; // 存放文件名,并非含有路径的名字
ArrayList files = new ArrayList(); // 存放文件对象
try {
FileOutputStream fileOut = new FileOutputStream(path + "Excel.zip");
ZipOutputStream zipos = new ZipOutputStream(fileOut);
File rootDir = new File(dir);
listFile(rootDir, fileNames, files);
for (int i = 0; i < files.size(); i++) {
FileInputStream fileIn = new FileInputStream( (File) files.get(i));
zipos.putNextEntry(new ZipEntry( (String) fileNames.get(i)));
byte[] buffer = new byte[1024];
while (fileIn.read(buffer) != -1) {
zipos.write(buffer);
zipos.flush();
}
zipos.closeEntry();
fileIn.close();
}
zipos.close();
}
catch (IOException io) {
io.printStackTrace();
throw new Exception("Zip压缩文件保存失败!");
}
return zipurl;
}
private static void listFile(File parentFile, List nameList, List fileList) {
if (parentFile.isDirectory()) {
File[] files = parentFile.listFiles();
for (int i = 0; i < files.length; i++) {
listFile(files[i], nameList, fileList);
}
}
else {
fileList.add(parentFile);
nameList.add(parentFile.getName());
}
}
JSP:
<%@ page contentType="text/html;charset=gb2312" import="com.jspsmart.upload.*,java.io.*,java.sql.*,oracle.sql.*,org.apache.log4j.*" %><jsp:useBean id="db" scope="page" class="com.ehub.DBDriver"/><%
ArrayList excelNames = new ArrayList();
ArrayList newNames = new ArrayList();
for(int i=0;i<excelNames.size();i++){
String excelid = excelNames.get(i).toString();
download.setExcelId(excelid);
String filename=download.getExcelId();
String fileUrl = path + "/" + filename;
String filePath = download.getFilepath(excelid,fileUrl); // ??excel??
newNames.add(i,filename);
}
String zipPath = download.getZipFilepath(path,newNames);
java.io.File rootDir = new java.io.File(path);
download.delAllFile(rootDir);
download.isAllCheckOut(excelNames);
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
su.setContentDisposition(null);
su.downloadFile(zipPath);