909422229_JavaWeb对列表数据整体打包压缩下载

来源:互联网 发布:虚拟展厅设计软件 编辑:程序博客网 时间:2024/06/04 01:35

收到客户的需求,要求以一定的格式对文件进行命名,并下载。压缩包内分别有各自的文件夹。对界面上用户查询到的数据进行整体打包下载。

对此进行记录,方便以后用到的地方提供一定的思路。


package zxqy.module.postcount.action;



import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import ezweb.modules.config.datas.utils.FileUtils;
import xsf.Config;
import xsf.IContextDictionary;
import xsf.data.DBManager;
import xsf.data.DataRow;
import xsf.data.DataSourceFactory;
import xsf.data.DataTable;
import xsf.data.IDataSource;
import xsf.util.StringHelper;
import xsf.web.HttpContext;
import xsf.web.IAction;
import zxqy.module.postcount.util.CopyFolderUtil;


/**
 * @description 发文统计附件下载
 * @author wangsh
 * @date 2017年05月05日
 */
public class DownLoadAction implements IAction {
private String temp = "";


@Override
public String excute(HttpContext context, IContextDictionary icdt) {
// 接收ID
String info_id = icdt.getString("INFO_ID");
// 文号名称
String wh = icdt.getString("WH");
// 生成文件文件夹名称
String folder = "[发送文件统计]";
temp = "F:\\" + folder + File.separator;
File ft = new File(temp);
if (!ft.exists()) {
ft.mkdirs();
}
// 下载压缩包临时文件夹
String down = "F:\\down";
File fileDown = new File(down);
if (!fileDown.exists()) {
fileDown.mkdirs();
}
// 根据ID获取条件
ifTermSql(info_id, icdt);
if (StringHelper.isNullOrEmpty(info_id)) {
// 打包下载时压缩包命名
String newFolder = "";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
String format = df.format(new Date());
newFolder = format + "[发送文件统计]";
// 整体打包压缩
cutDownFile(info_id, newFolder, context);
}
return null;
}


// 根据ID打包下载
private void ifTermSql(String info_id, IContextDictionary icdt) {
// 根据是否传入info_id,判断条件是下载全部或者指定文件下载
if (StringHelper.isNullOrEmpty(info_id)) {
// 添加数据源
IDataSource dataSource = DataSourceFactory.create(136204L);
DataTable table = dataSource.query(icdt);
// 获取INFO_ID
if (table.getTotal() > 0) {
for (DataRow row : table.getRows()) {
info_id = row.getString("INFO_ID");
// 获取条件执行sql
getFileStream(info_id);
}
}
}
// 获取条件执行sql
getFileStream(info_id);
}
// 执行条件SQL,获取数据
private void getFileStream(String infoId) {
String sql_ = "";
sql_ = "SELECT m.CONTENT,n.NRBT,n.info_id,g.wh,g.bt FROM G_NR n INNER JOIN MMDATA m ON m.ID=n.MNR INNER JOIN g_infos g ON g.id=n.info_id WHERE n.INFO_ID IN("
+ infoId + ")";
// 获得当前数据库链接
Connection conn = DBManager.getConnection(Config.CONNECTION_KEY);
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(sql_);
rs = stmt.executeQuery();
while (rs.next()) {
String fileName = rs.getString("NRBT");
InputStream fis = rs.getBinaryStream("CONTENT");
String wh = rs.getString("WH");
String bt = rs.getString("BT");
String fileName2 = wh + bt;
this.download(fileName, fis, fileName2);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


// 下载到临时目录
private void download(String fileName, InputStream in, String fileName2) {
OutputStream out = null;
try {
// 下载生成到临时目录
File file = new File(temp + fileName2 + File.separator);
if (!file.exists()) {
file.mkdirs();
}
File file2 = new File(temp + fileName2 + File.separator + fileName);
out = new FileOutputStream(file2);
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) > -1) {
out.write(b, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


// 打包压缩
private void cutDownFile(String info_id, String folder, HttpContext context) {
String url = "F:\\down";
String temp = "F:\\[发送文件统计]";
File file_temp = new File(temp);
CopyFolderUtil.zip(temp);
deleteDirectory(file_temp);
// 为压缩包进行命名,防止乱码
try {
folder = new String(folder.getBytes(), "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 设置下载压缩包命名
HttpServletResponse response = context.getResponse();
response.setContentType("application/x-download;charset=UTF-8");
String zipName = folder + ".zip";
response.addHeader("Content-Disposition", "attachment;filename=\""
+ zipName + "\"");
// 开始打包文件流
ServletOutputStream out = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
File file = new File(url);
File[] files = file.listFiles();
try {
byte[] bufs = new byte[1024];
out = response.getOutputStream();
for (File f : files) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(f.getName());
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(f);
// 缓冲区
bis = new BufferedInputStream(fis);
int read = 0;
while ((read = bis.read(bufs)) != -1) {
out.write(bufs, 0, read);
}
fis.close();
// 删掉文件
f.delete();
}
} catch (Exception e) {
} finally {
try {
// out.closeEntry();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
// 删掉文件夹
file.delete();
}
}
// 删除文件夹  
    private static void deleteDirectory(File file) {  
        if (file.isFile()) {// 表示该文件不是文件夹  
            file.delete();  
        } else {  
            // 首先得到当前的路径  
            String[] childFilePaths = file.list();  
            for (String childFilePath : childFilePaths) {  
                File childFile = new File(file.getAbsolutePath() + "/" + childFilePath);  
                deleteDirectory(childFile);  
            }  
            file.delete();  
        }  
    }

}

package zxqy.module.postcount.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


import org.apache.tools.zip.ZipOutputStream;




/**
 * 复制文件
 * 
 * @author wangsh
 * 
 */
public class CopyFolderUtil {
public static void zip(String inputFileName) {
String zipFileName = "F:\\down\\test.zip"; // 打包后文件名字
zip(zipFileName, new File(inputFileName));
}
private static void zip(String zipFileName, File inputFile) {
ZipOutputStream out = null;

//System.setProperty("sun.zip.encoding", System.getProperty("sun.jnu.encoding"));
try {
out = new ZipOutputStream(new FileOutputStream(zipFileName));
out.setEncoding("UTF-8");

zip(out, inputFile, "");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


private static void zip(ZipOutputStream out, File f, String base) {
FileInputStream in = null;
if (f.isDirectory()) {
File[] fl = f.listFiles();
try {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));

base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} catch (IOException e) {


}
} else {
try {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
in = new FileInputStream(f);
int b;
System.out.println(base);
while ((b = in.read()) != -1) {
out.write(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}


}
}
}

1 0