<%@page import="org.springframework.util.Base64Utils"%> <%@page import="com.hanweb.common.util.file.OSSFileUtil"%> <%@page import="com.hanweb.common.util.file.BOSFileUtil"%> <%@page import="com.hanweb.common.util.ip.IpUtil"%> <%@page import="com.hanweb.common.util.DateUtil"%> <%@page import="com.hanweb.jcms.plugins.download.service.DownloadBLF"%> <%@page import="com.hanweb.jcms.util.io.DownFile"%> <%@page import="com.hanweb.common.util.SpringUtil"%> <%@page import="com.hanweb.jcms.service.website.Jcms_WebinfomationBLF"%> <%@page import="com.hanweb.common.util.file.IFileUtil"%> <%@page import="com.hanweb.jcms.util.xml.XMLFile"%> <%@page import="com.hanweb.common.util.mvc.Script"%> <%@page import="com.hanweb.jcms.entity.Jcms_AttachEntity"%> <%@page import="com.hanweb.common.util.NumberUtil"%> <%@page import="com.hanweb.jcms.service.filemanager.Jcms_AttachBLF"%> <%@page import="org.apache.commons.logging.LogFactory"%> <%@page import="org.apache.commons.logging.Log"%> <%@page import="com.hanweb.common.util.StringUtil"%> <%@page contentType="text/html;charset=UTF-8"%> <%@page import="java.net.URLEncoder"%> <%@page import="java.util.regex.Pattern"%> <%@page import="java.util.regex.Matcher"%> <%@ page import="com.hanweb.common.BaseInfo" %> <%@ page import="java.io.*" %> <%@include file="./config.jsp"%> <% System.out.println("进入downfile.jsp"); String strFileName = StringUtil.getSafeString(request.getParameter("filename")); String i_classid = StringUtil.getSafeString(request.getParameter("classid")); String pathfile = StringUtil.getSafeString(request.getParameter("pathfile")); Log logger = LogFactory.getLog(getClass()); Script script = Script.getInstanceOnly(); if (strFileName.contains("../")) { out.println(script.addScript("alert('文件路径包含非法参数!');").getScript()); return; } int etype = 0;//是否可以连接数据库 0 可以 1不可以 if (strFileName.length() == 0) { out.println(script.addScript("alert('未指定要下载文件的文件名!');").getScript()); logger.debug("未指定要下载文件的文件名!"); return; } if (pathfile != null && StringUtil.getString(pathfile).length() > 0) { if (pathfile.contains("../")) { out.println(script.addScript("alert('文件路径包含非法参数!');").getScript()); return; } if (strFileName.indexOf(".") > 0) { strFileName = strFileName.substring(0, strFileName.indexOf(".")); } String encodeName = ""; if (StringUtil.isChinese(strFileName)) { try { encodeName = java.net.URLEncoder.encode(strFileName); } catch (Exception e) { e.printStackTrace(); } pathfile = pathfile.replaceAll(strFileName, encodeName); } Jcms_WebinfomationBLF webinfomationBLF = Jcms_WebinfomationBLF.getInstance(); String domains = webinfomationBLF.findDomainFromWebInfo(NumberUtil.getInt(strWebID)); String strAttachUrl = (domains + "/" + pathfile); strAttachUrl = strAttachUrl.replaceAll("//", "/"); strAttachUrl = strAttachUrl.replaceAll("\r", ""); strAttachUrl = strAttachUrl.replaceAll("\n", ""); strAttachUrl = strAttachUrl.replaceAll("\n\r", ""); out.println(script.addScript("window.open('http://" + strAttachUrl + "')").getScript()); return; } IFileUtil fileUtil = (IFileUtil) SpringUtil.getBean("FileUtil"); Jcms_AttachBLF attachBlf = Jcms_AttachBLF.getInstance().init(strAppID, NumberUtil.getInt(strWebID)); Jcms_AttachEntity attachEn = null; try { attachEn = attachBlf.findFileName(strFileName); } catch (Exception e) { etype = 1; } if (attachEn == null) { if ("".equals(i_classid)) { out.println(script.addScript("alert('文件不存在!');").getScript()); return; } else { //数据移植直接放进去的附件,没有入库 String strFilePath ; if (strFileName.contains("attatches")) { strFilePath = fileUtil.getAbsolutePath("jcms_files/jcms" + strAppID + "/web" + strWebID + "/site" + strFileName);//物理路径 } else { strFilePath = fileUtil.getAbsolutePath("jcms_files/jcms" + strAppID + "/web" + strWebID+ "/site/attach/" + i_classid + "/" + strFileName);//物理路径 } if (fileUtil.exists(strFilePath)) { attachEn = new Jcms_AttachEntity(); attachEn.setVc_name(strFileName); attachEn.setI_typeid(NumberUtil.getInt(i_classid)); } else { out.println(script.addScript("alert('文件不存在!');").getScript()); return; } } } String fileType = ""; if (strFileName.lastIndexOf(".") >= 0 && strFileName.lastIndexOf(".") < strFileName.length() - 1) { fileType = strFileName.substring(strFileName.lastIndexOf(".") + 1); } int classId = attachEn.getI_typeid();//类别ID String downloadname = ""; downloadname = attachEn.getVc_name();//下载显示名 if (downloadname == null || downloadname.trim().length() == 0) { downloadname = strFileName; } String strFilePath = ""; if (strFileName.indexOf("attatches") != -1) { strFilePath = fileUtil .getAbsolutePath("jcms_files/jcms" + strAppID + "/web" + strWebID + "/site" + strFileName);//物理路径 } else { strFilePath = fileUtil.getAbsolutePath("jcms_files/jcms" + strAppID + "/web" + strWebID + "/site/attach/" + classId + "/" + strFileName);//物理路径 } if (!fileUtil.exists(strFilePath) || strFilePath.toLowerCase().endsWith(".xml") || strFilePath.toLowerCase().endsWith(".jsp")) { logger.debug(" downfile:文件不存在!"); out.println(script.addScript("alert('下载失败,文件不存在!');").getScript()); return; } XMLFile xmlFile = new XMLFile(); String webPath = application.getRealPath("") + "/jcms_files/jcms" + strAppID + "/web" + strWebID + "/site/"; String confPath = webPath + "module/download/config/config.xml"; String webtype = xmlFile.getContent("webtype", confPath); //1:内网 2:外网 String filedownload = ""; if (strFileName.indexOf("attatches") != -1) { filedownload = fileUtil .getAbsolutePath("jcms_files/jcms" + strAppID + "/web" + strWebID + "/site" + strFileName);//下载路径 } else { filedownload = fileUtil.getAbsolutePath("jcms_files/jcms" + strAppID + "/web" + strWebID + "/site/attach/" + classId + "/" + strFileName);//下载路径 } //pdf文件在文章页中直接预览 String filenamedisplay = ""; String userAgent = request.getHeader("USER-AGENT"); if (userAgent.lastIndexOf("Safari") > -1 && userAgent.lastIndexOf("Chrome") == -1) { filenamedisplay = new String(downloadname.getBytes("UTF-8"), "ISO8859-1"); } else if (userAgent != null && userAgent.toLowerCase().indexOf("firefox") > -1) { filenamedisplay = "=?UTF-8?B?" + (new String(Base64Utils.encodeToString(downloadname.getBytes("UTF-8")))) + "?="; } else { filenamedisplay = URLEncoder.encode(downloadname, "UTF-8"); } //attachEn 为空 没有名称默认为 url的文件名称 if (filenamedisplay.trim().length() == 0) { filenamedisplay = strFileName; } try { out.clear(); out = pageContext.pushBody(); } catch (Throwable e) { e.printStackTrace(); } DownloadBLF downblf = SpringUtil.getBean(DownloadBLF.class); try { if (userAgent.contains("iPhone") || userAgent.contains("iPad")) { if ("xls".equals(fileType) || "xlsx".equals(fileType)) { if("xls".equals(fileType)){ response.setContentType("application/vnd.ms-excel;charset=UTF-8"); }else{ response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"); } if (!getFile(filedownload, filenamedisplay, response,"UTF-8", request,false)) { out.println(script.addScript("alert('下载失败,文件可能不存在!');").getScript()); } else { //无法连接数据库 不存表 if (etype == 0) { downblf.addDownloadRecord(strFileName, DateUtil.getCurrDateTime(), request.getContextPath(), request.getHeader("user-agent"), IpUtil.getIp(), NumberUtil.getInt(strWebID)); } } } else { if ("txt".equals(fileType)) { response.setContentType("text/html;charset=gb2312"); } if ("pdf".equals(fileType)) { response.setContentType("application/pdf;charset=UTF-8"); } if ("docx".equals(fileType)) { response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8"); } if ("doc".equals(fileType)) { response.setContentType("application/msword;charset=UTF-8"); } RequestDispatcher dis = application.getRequestDispatcher("/jcms_files/jcms" + strAppID + "/web" + strWebID + "/site/attach/" + classId + "/" + strFileName); if (dis != null) { dis.forward(request, response); if (etype == 0) { downblf.addDownloadRecord(strFileName, DateUtil.getCurrDateTime(), request.getContextPath(), request.getHeader("user-agent"), IpUtil.getIp(), NumberUtil.getInt(strWebID)); } } else { out.println(script.addScript("alert('下载失败,文件可能不存在!');").getScript()); } } } else if (userAgent.contains("Android")) { if (!getFile(filedownload, filenamedisplay, response, "UTF-8", request, false)) { out.println(script.addScript("alert('下载失败,文件可能不存在!');").getScript()); } else { if (etype == 0) { downblf.addDownloadRecord(strFileName, DateUtil.getCurrDateTime(), request.getContextPath(), request.getHeader("user-agent"), IpUtil.getIp(), NumberUtil.getInt(strWebID)); } } } else { //oss和bos下浏览器无法直接打开pdf文件 if ("pdf".equals(fileType) && fileUtil.getImplClazz() != OSSFileUtil.class && fileUtil.getImplClazz() != BOSFileUtil.class) { response.setHeader("Content-Disposition", "inline; filename=" + filenamedisplay); response.setContentType("application/pdf;charset=UTF-8"); RequestDispatcher dis = application.getRequestDispatcher("/jcms_files/jcms" + strAppID + "/web" + strWebID + "/site/attach/" + classId + "/" + strFileName); if (dis != null) { dis.forward(request, response); if (etype == 0) { downblf.addDownloadRecord(strFileName, DateUtil.getCurrDateTime(), request.getContextPath(), request.getHeader("user-agent"), IpUtil.getIp(), NumberUtil.getInt(strWebID)); } } else { out.println(script.addScript("alert('下载失败,文件可能不存在!');").getScript()); } } else { if (!getFile(filedownload, filenamedisplay, response, "UTF-8", request, false)) { out.println(script.addScript("alert('下载失败,文件可能不存在!');").getScript()); } else { //无法连接数据库 不存表 if (etype == 0) { downblf.addDownloadRecord(strFileName, DateUtil.getCurrDateTime(), request.getContextPath(), request.getHeader("user-agent"), IpUtil.getIp(), NumberUtil.getInt(strWebID)); } } } } } catch (Exception e) { e.printStackTrace(); } finally { response.flushBuffer(); } %> <%! private final static Log logger = LogFactory.getLog(DownFile.class); /** * 下载文件 * * @param strFile 文件路径+文件名 * @param downFileName 下载文件命名 * @param response reponse对象 * @param charset 编码 * @return */ public static boolean getFile(String strFile, String downFileName, HttpServletResponse response, String charset, HttpServletRequest request, boolean isLocal) { strFile = StringUtil.getString(strFile); downFileName = StringUtil.getString(downFileName); if (strFile.length() == 0 || downFileName.length() == 0) { return false; } int nPot = strFile.lastIndexOf("/"); String strFileName = ""; if (nPot != -1) { strFileName = strFile.substring(nPot + 1); } String strFilePath = strFile.replace(strFileName, ""); return getFile(strFilePath, strFileName, downFileName, response, charset, request, isLocal); } /** * 下载文件 * * @param strFilePath 文件路径 * @param strFileName 文件名称 * @param downFileName 下载文件命名 * @param response reponse对象 * @param charset 编码 * @return */ public static boolean getFile(String strFilePath, String strFileName, String downFileName, HttpServletResponse response, String charset, HttpServletRequest request, boolean isLocal) { strFilePath = StringUtil.getString(strFilePath); strFileName = StringUtil.getString(strFileName); downFileName = StringUtil.getString(downFileName); if (strFilePath.length() == 0 || strFileName.length() == 0 || downFileName.length() == 0 || request == null){ return false; } if (!strFilePath.endsWith("/")) { strFilePath += "/"; } response.setContentType("application/octet-stream"); //使本地文件名显示不为乱码 response.setContentType("text/html;charset=" + charset); response.setHeader("Content-Disposition", "attachment; filename=\"" + downFileName + "\""); String fileType = strFileName.substring(strFileName.lastIndexOf(".") + 1); if ("txt".equals(fileType)) { response.setContentType("text/html;charset=gb2312"); } if ("pdf".equals(fileType)) { response.setContentType("application/pdf;charset=UTF-8"); } if ("docx".equals(fileType)) { response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8"); } if ("doc".equals(fileType)) { response.setContentType("application/msword;charset=UTF-8"); } if ("xls".equals(fileType)) { response.setContentType("application/vnd.ms-excel;charset=UTF-8"); } if ("xlsx".equals(fileType)){ response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"); } IFileUtil fileUtil = (IFileUtil )SpringUtil.getBean("FileUtil"); long len = 0; if(isLocal){ String realPath = BaseInfo.getRealPath().replaceAll("\\\\", "/"); strFilePath = strFilePath.replaceAll("\\.\\./", "").replaceAll("\\\\", "/"); /*判断路径合法性,过滤 非系统内 || jsp文件 */ if (strFilePath.indexOf(realPath) == -1 || strFilePath.endsWith("jsp") || strFilePath.indexOf(00) != -1) { return false; } File file = new File(strFilePath + strFileName); if (!file.exists()) { return false; } len = file.length(); if (downFileName.endsWith(".docx") || downFileName.endsWith(".xlsx") || downFileName.endsWith(".pptx")) { response.setHeader("Content-Length", Long.toString(len)); } }else{ /*判断路径合法性,过滤 非系统内 || jsp文件 */ if (strFilePath.endsWith("jsp") || strFilePath.indexOf(00) != -1) { return false; } if (!fileUtil.exists(strFilePath + strFileName)) { return false; } len = fileUtil.getFileSize(strFilePath + strFileName); response.setHeader("Content-Length", Long.toString(len)); } byte[] buffer = new byte[1024]; // 缓冲区 BufferedOutputStream output = null; BufferedInputStream input = null; try { output = new BufferedOutputStream(response.getOutputStream()); if(isLocal){ input = new BufferedInputStream(new FileInputStream(strFilePath + strFileName)); }else{ input = new BufferedInputStream(fileUtil.readFileToInputSteam(strFilePath + strFileName)); } int n = -1; while ((n = input.read(buffer, 0, 1024)) > -1) { output.write(buffer, 0, n); } response.flushBuffer(); } catch (Exception e) { logger.error(null, e); } finally { if (input != null) { try { input.close(); } catch (Exception closeExp) { logger.error(null, closeExp); } finally { } } if (output != null) { try { output.close(); } catch (Exception closeExp) { } } } return true; } %>