前台请求
function downsourcedataList(){
if($("#idList").val() == ''){
$.messager.alert('提示', '当前未选中任何数据,请选择!', 'info');
return ;
}
window.location.href = '<%=basePath%>revenueStatistics/downsourcedataList.do?idList='+$("#idList").val();
}
下载文件工具类
package com.fh.util;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
public class FileDownload {
/**
* @param response
* @param filePath //文件完整路径(包括文件名和扩展名)
* @param fileName //下载后看到的文件名
* @return 文件名
*/
public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{
byte[] data = FileUtil.toByteArray2(filePath);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
response.flushBuffer();
}
}
打包下载
/**
* 批量下载源数据
* @param response
*/
@RequestMapping("/downsourcedataList")
public void downsourcedataList(HttpServletResponse response) {
logger.info("收入统计-批量下载源数据excel,开始...");
try {
PageData pd = this.getPageData();
List<String> createFilesPath = new ArrayList<String>();
String[] idList = pd.getString("idList").split(",");
for(String s : idList) {
String id = URLEncoder.encode(s, "UTF-8");
pd = new PageData();
pd.put("id", id);
String queryTime = revenueStatisticsService.getQueryTime(pd);
createFilesPath.add(PathUtil.getClasspath() + Const.REVENUESTATISTICS + id + "实验室收入统计源数据" + queryTime + ".xlsx");
}
String zipPath = PathUtil.getClasspath() + Const.FILEPATHFILE_REVENUESTATISTICS;
String zipName = "实验室收入统计源数据-合计"+ createFilesPath.size() +"个报告.zip";
String strZipPath = zipPath + zipName;
byte[] buffer = new byte[10240];
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
File[] file = new File[createFilesPath.size()];
for (int i = 0; i < createFilesPath.size(); i++) {
file[i] = new File(createFilesPath.get(i));
}
for (int i = 0; i < file.length; i++) {
FileInputStream fis = new FileInputStream(file[i]);
out.putNextEntry(new ZipEntry(file[i].getName()));
// 设置压缩文件内的字符编码,不然会变成乱码
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
FileDownload.fileDownload(response, zipPath + zipName, zipName);
} catch (Exception e) {
logger.error(e.toString());
}
logger.info("收入统计-批量下载源数据excel,结束...");
}