/**最近在项目中做了个多文件下载,分享给大家,少废话 上代码
/**
* 多文件下载(将多文件打包成zip 下载到用户桌面) mxk
* @param response
* @param request
* @throws Exception
*/
@RequestMapping("/downPrintLodopFile")
public void downPrintLodopFile(HttpServletResponse response,HttpServletRequest request) throws Exception{
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
String path = desktopDir.getAbsolutePath();//获取用户桌面路径
String dbpath = request.getParameter("filePath");//获取文件路径
String fileName = request.getParameter("fileName");//获取文件名
String[] fileNames = fileName.split("/");
String base_name = "下载文件";
String fileZip = base_name + ".zip"; // 拼接zip文件,之后下载下来的压缩文件的名字
String filePath = path + fileZip;// 之后用来生成zip文件
String localPath=ResourceUtil.getConfigByName("webUploadpath");
String url = localPath+"/"+dbpath;
// 创建临时压缩文件
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
ZipOutputStream zos = new ZipOutputStream(bos);
ZipEntry ze = null;
for (int i = 0; i < fileNames.length; i++) {// 将所有需要下载的文件都写入临时zip文件
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(url+"/"+fileNames[i]));
ze = new ZipEntry(
fileNames[i]);
zos.putNextEntry(ze);
int s = -1;
while ((s = bis.read()) != -1) {
zos.write(s);
}
bis.close();
}
zos.flush();
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 以上,临时压缩文件创建完成
// 进行浏览器下载
// 获得浏览器代理信息
String agent = request.getHeader("User-Agent").toUpperCase();
// 判断浏览器代理并分别设置响应给浏览器的编码格式
String finalFileName = null;
if ((agent.indexOf("MSIE") > 0)
|| ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
finalFileName = URLEncoder.encode(fileZip, "UTF-8");
else {
finalFileName = new String(fileZip.getBytes("UTF-8"), "ISO8859-1");
}
response.setContentType("application/x-download");// 告知浏览器下载文件,而不是直接打开,浏览器默认为打开
response.setHeader("Content-Disposition", "attachment;filename=\""
+ finalFileName + "\"");// 下载文件的名称
//输出到本地
ServletOutputStream servletOutputStream = response.getOutputStream();
DataOutputStream temps = new DataOutputStream(servletOutputStream);
DataInputStream in = new DataInputStream(new FileInputStream(filePath));// 浏览器下载临时文件的路径
byte[] b = new byte[2048];
File reportZip = new File(filePath);// 之后用来删除临时压缩文件
try {
while ((in.read(b)) != -1) {
temps.write(b);
}
temps.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (temps != null)
temps.close();
if (in != null)
in.close();
if (reportZip != null)
reportZip.delete();// 删除服务器本地产生的临时压缩文件
servletOutputStream.close();
}
}
多文件下载(将多文件打包成zip 下载到用户桌面)
最新推荐文章于 2024-02-22 11:58:04 发布