1.整体功能演示
附件管理包括以下功能:上传附件、删除附件、下载单个文件、打包下载多个文件。全部功能演示如下:
2.程序入口
//打开上传附件界面 function selfUploadFile() { var url = "<%=request.getContextPath()%>/scripts/common/document/DocumentList.jsp?fileID=<%=oFile.getFILEID()%>&r="+new Date().getTime(); var rtn = window.showModalDialog(url,document,'dialogWidth:650px;dialogHeight:500px;dialogLeft:600px;dialogTop:250px;scroll:no;'); }
3.界面设计
4.上传附件功能,实现选择文件后自动上传,并刷新列表界面
目标:为点击按钮,打开文件选择框,选择文件后自动上传,上传结束后,进行提示,并刷新列表界面。
初始设计:一开始,设计为在form表单里放一个隐藏的input type="file"控件,一个“上传”按钮。在“上传”按钮的点击事件里用js调用input type="file"控件的click()事件,弹出文件选择框选择文件后,js提交form表单。结果,一提交,文件框自动清空,后台获取不到提交的文件。经测试,必须手动点击文件框选择文件后提交后台才能获取到文件。
改进设计:在“上传”按钮上放置form表单,表单enctype="multipart/form-data",表单里放一个input type="file"控件,
设置向左偏移并透明margin-left: -80px;FILTER: alpha(opacity=0),
文件选择改变后提交表单onchange="document.getElementById('form').submit();",
后台处理程序保存文件action="<%=request.getContextPath()%>/scripts/common/document/UploadFiles.jsp?referenceID=<%=referenceID%>"
后台保存上传的文件后自动刷新页面String url = request.getHeader("referer");response.sendRedirect(url);
前端代码:
后台处理程序核心代码(UploadFiles.jsp):
DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 1024 * 20);////设置上传工厂的限制 ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * 20);//设置最大的上传限制 List items = upload.parseRequest(request);//处理HTTP请求,items是所有的表单项 for(int i =0; i < items.size(); i ++){ FileItem fileItem=(FileItem)items.get(i); String name = fileItem.getName(); if(name==null || name.trim().length()==0) { continue; } name = name.substring(name.lastIndexOf("\\")+1); String title = name.substring(0,name.lastIndexOf('.')); int size = (int)fileItem.getSize(); String contentType=fileItem.getContentType(); byte[] fileContent=fileItem.get(); Attachment attachment = new Attachment(); attachment.setFileName(name); attachment.setFileContentType(contentType); attachment.setFileSize(size); attachment.setFileContent(fileContent); attachment.setFileTitle(title); attachment.setReferenceID(referenceID); // attachment.setFileType(fileType); attachment.setUploader(userid); String result = ga.update("xt_document",attachment); }
5.ajax实现删除文件,并刷新界面
5.1 台前ajax请求删除
var url = "<%=request.getContextPath()%>/scripts/common/document/DeleteFiles.jsp"; $.ajax({ cache: true, type: "POST", dataType:"json", url:url, data:{fileIDs:fileIDs}, async: false, error: function(request) { alert("error"); }, success: function(data) { if(data.code==0) { alert(data.msg); }else { alert(data.msg); reload.href = window.location.href; reload.click(); } } });
5.2 后台删除处理程序核心代码(DeleteFiles.jsp)
request.setCharacterEncoding("UTF-8"); JSONObject retJson = new JSONObject(); String code = "1"; String msg = "操作成功"; String data = ""; String p_userid = (String)session.getAttribute("userid"); ICommonService gd = (ICommonService)ServiceHelper.getService(CommonConstants.COMMON_SERVICE); String fileIDs = StringUtility.toTrimString(request.getParameter("fileIDs")); Set<String> fileIDsSet = new HashSet<String>(); try{ if(fileIDs!=null && fileIDs.trim().length()>0) { String[] fileIDsArr = fileIDs.split(","); gd.deleteData("XT_Document", "FileID/[@0]", fileIDsArr); } retJson.put("code", code); retJson.put("msg", msg); retJson.put("data", ""); out.write(retJson.toString()); } catch (Exception e) { e.printStackTrace(System.out); code = "0"; msg = e.getMessage(); retJson.put("code", code); retJson.put("msg", msg); retJson.put("data", ""); out.write(retJson.toString()); }
5.3 使用JS刷新showModalDialog窗口,JS刷新模式对话框
5.3.1 在showModalDialo窗口的<html>与<Head>之间加上<base target="_self"> ,使这个页面上链接都在本窗口中打开
5.3.2 在页面中加一个隐藏<a>标签,如:<a id="reload" href="" tyle="display:none">reload</a>
5.3.3 在JS中把当前页面的地址赋到<a>的href属性中,执行单击事件。
reload.href = window.location.href ;
reload.click();
说明:reload为定义的<a>标签的ID
6.文件下载功能
6.1 前台调用下载功能js
function downloadAttachment()//下载 { var fileIDs = getSelectedIDs(); if(fileIDs==null || fileIDs=="" || fileIDs==undefined) { alert("请选择记录"); return; } var url = "<%=request.getContextPath()%>/scripts/common/document/DownloadFiles.jsp?fileIDs="+fileIDs; var rtn = window.open(url); } function downloadAllAttachment()//下载全部 { var url = "<%=request.getContextPath()%>/scripts/common/document/DownloadFiles.jsp?referenceID=<%=referenceID%>"; var rtn = window.open(url); }
6.1 单个文件下载核心代码(DownloadFiles.jsp)
String fileID = fileIDsSet.iterator().next(); Attachment att = gatt.getAttachment("XT_Document",fileID); String fileName = new String(att.getFileName().getBytes(),"iso-8859-1"); byte[] context = att.getFileContent(); //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); //2.设置文件头:最后一个参数是设置下载文件名 response.setHeader("Content-Disposition", "attachment;fileName="+fileName); java.io.OutputStream os = response.getOutputStream(); os.write(context); //注意看以下几句的使用 os.flush(); os.close(); response.flushBuffer(); out.clear(); out = pageContext.pushBody();
6.2多个文件打包下载核心代码(DownloadFiles.jsp)
response.reset(); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment;filename=attachment.zip"); java.io.OutputStream os = response.getOutputStream(); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); Iterator<String> it = fileIDsSet.iterator(); while(it.hasNext()) { String fileID = it.next(); Attachment att = gatt.getAttachment("XT_Document",fileID); String fileName = att.getFileName(); String fileTitle = att.getFileTitle(); byte[] context = att.getFileContent(); int fileSize = att.getFileSize(); String strFileSize = ""; if (fileSize > 1024) { strFileSize = fileSize / 1024 + "KB"; } else { strFileSize = fileSize + "Byte"; } ZipArchiveEntry entry = new ZipArchiveEntry(fileName); zos.putArchiveEntry(entry); zos.write(context); zos.closeArchiveEntry(); } zos.flush(); zos.close(); //注意看以下几句的使用 os.flush(); os.close(); response.flushBuffer(); out.clear(); out = pageContext.pushBody();
6.3 获取和保存sql server image类型字段值的方法
6.4 servlet下载文件中文文件名无法识别的问题
7.全部代码清单
7.1 DocumentList.jsp
<%@page import="java.text.SimpleDateFormat"%> <%@page import="java.text.DateFormat"%> <%@page import="com.costech.common.helper.AuthHelper" %> <%@page import="com.costech.common.util.StringUtility" %> <%@page import="com.costech.common.constants.CommonConstants"%> <%@page import="com.costech.common.service.ICommonService"%> <%@page import="com.costech.common.helper.ServiceHelper"%> <%@page import="com.costech.common.bean.Attachment" %> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ICommonService gd = (ICommonService)ServiceHelper.getService(CommonConstants.COMMON_SERVICE); String referenceID = StringUtility.toTrimString(request.getParameter("fileID")); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>附件管理</title> <base target="_self"> <script src='<%=request.getContextPath() %>/include/jquery-1.11.1.min.js'></script> <SCRIPT language=JavaScript src="<%=request.getContextPath()%>/include/list.js"></SCRIPT> <style type="text/css"> table{border-right:1px solid #B2CCE5;border-bottom:1px solid #B2CCE5;font-size: 12px;} table th{background-color:#E0EAF7; border-left:1px solid #B2CCE5;border-top:1px solid #B2CCE5;color:#01245E;} table td{border-left:1px solid #B2CCE5;border-top:1px solid #B2CCE5;} </style> <script language="JavaScript" type="text/JavaScript"> function getSelectedIDs() { var fileIDs = ""; var i=0; $("input[name='chxCheckFileID']").each(function(){ var fileID = $(this).val(); if($(this).is(":checked") && fileID !== null && fileID !== undefined && fileID !== '') { if(i==0) { fileIDs = fileID; }else { fileIDs = fileIDs+","+fileID; } i++; } }); return fileIDs; } function deleteAttachment() { var fileIDs = getSelectedIDs(); if(fileIDs==null || fileIDs=="" || fileIDs==undefined) { alert("请选择记录"); return; } if(!confirm("确认要删除?")) { return; } var url = "<%=request.getContextPath()%>/scripts/common/document/DeleteFiles.jsp"; $.ajax({ cache: true, type: "POST", dataType:"json", url:url, data:{fileIDs:fileIDs}, async: false, error: function(request) { alert("error"); }, success: function(data) { if(data.code==0) { alert(data.msg); }else { alert(data.msg); reload.href = window.location.href; reload.click(); } } }); } function downloadAttachment()//下载 { var fileIDs = getSelectedIDs(); if(fileIDs==null || fileIDs=="" || fileIDs==undefined) { alert("请选择记录"); return; } var url = "<%=request.getContextPath()%>/scripts/common/document/DownloadFiles.jsp?fileIDs="+fileIDs; var rtn = window.open(url); } function downloadAllAttachment()//下载全部 { var url = "<%=request.getContextPath()%>/scripts/common/document/DownloadFiles.jsp?referenceID=<%=referenceID%>"; var rtn = window.open(url); } function allCheckbox_onclick(obj) { $("input[name='chxCheckFileID']").attr("checked",obj.checked); } </script> </head> <body> <div style="width: 100%;height: 20px;background-color: #E0EAF7;"> <button type="button" style="valign: middle;cursor: hand;background-color: transparent; border: 0;"> <img src="<%=request.getContextPath() %>/image/common/attach_upload.gif" width="15" height="15" align="absbottom">上传 </button> <form id="form" action="<%=request.getContextPath()%>/scripts/common/document/UploadFiles.jsp?referenceID=<%=referenceID%>" method="post" enctype="multipart/form-data" style="display: inline;"> <input type="file" name="fileSelect" id="fileSelect" style="width: 0px;margin-left: -80px;FILTER: alpha(opacity=0);cursor: hand;" onchange="document.getElementById('form').submit();"/> </form> <button type="button" style="valign: middle;cursor: hand;background-color: transparent; border: 0;" onclick="deleteAttachment()" onmouseover="style.backgroundColor='white'" onMouseOut="style.backgroundColor='#E0EAF7'"> <img src="<%=request.getContextPath() %>/image/common/attach_delete.gif" width="15" height="15" align="absbottom">删除 </button> <button type="button" style="valign: middle;cursor: hand;background-color: transparent; border: 0;" onclick="downloadAttachment()" onmouseover="style.backgroundColor='white'" onMouseOut="style.backgroundColor='#E0EAF7'"> <img src="<%=request.getContextPath() %>/image/common/putintofolder.gif" width="15" height="15" align="absbottom">下载 </button> <button type="button" style="valign: middle;cursor: hand;background-color: transparent; border: 0;" onclick="downloadAllAttachment()" onmouseover="style.backgroundColor='white'" onMouseOut="style.backgroundColor='#E0EAF7'"> <img src="<%=request.getContextPath() %>/image/common/putintofolder.gif" width="15" height="15" align="absbottom">下载全部 </button> </div> <div style="height: 98%;OVERFLOW-Y: auto;border: 3px solid #B2CCE5;"> <table style="width: 100%;" cellspacing="0" cellpadding="0"> <thead> <tr> <th style="width:30px;text-align: center;"><input type="checkbox" onclick="allCheckbox_onclick(this)"/></th> <th style="width:30px;">序号</th> <th>文件名</th> <th>文件大小</th> <th>上传人</th> <th>上传时间</th> </tr> </thead> <tbody> <% String sql = "select d.FileID,d.FileName,d.FileSize,d.FileTitle,u.username Uploader,d.UploadDate from XT_Document d " +" left join xt_user u on d.Uploader=u.userid " +" where d.ReferenceID ='" + referenceID + "'"; List list = gd.getDataList(sql, Attachment.class); for(int i=0;i<list.size();i++) { Attachment att = (Attachment)list.get(i); int fileSize = att.getFileSize(); String strFileSize = ""; if (fileSize>1024*1024) { strFileSize = fileSize/1024/1024 + "M"; }else if(fileSize>1024) { strFileSize = fileSize/1024 + "KB"; } else { strFileSize = fileSize + "Byte"; } String uploadDate = ""; if(att.getUploadDate()!=null) { uploadDate = df.format(att.getUploadDate()); } %> <tr onmouseover="style.backgroundColor='#B2CCE5'" onmouseout="style.backgroundColor='<%=(i%2==0?"#FFFFFF":"#ECF6F9")%>'" style="background-color: <%=(i%2==0?"#FFFFFF":"#ECF6F9")%>"> <td style="text-align: center;"><input type="checkbox" name='chxCheckFileID' value="<%=att.getFileID() %>"/></td> <td style="text-align: center;"><%=i+1 %></td> <td><%=att.getFileName() %></td> <td><%=strFileSize %></td> <td><%=att.getUploader() %></td> <td><%=uploadDate %></td> </tr> <% } %> </tbody> </table> </div> <a id="reload" href="" tyle="display:none">reload</a> </body> </html>
7.2 UploadFiles.jsp
<%@page contentType="text/html;charset=utf-8"%> <%@ page language="java" import="java.util.List"%> <%@ page language="java" import="org.apache.commons.fileupload.*"%> <%@ page language="java" import="org.apache.commons.fileupload.disk.*"%> <%@ page language="java" import="org.apache.commons.fileupload.servlet.*"%> <%@page import="com.costech.common.util.StringUtility"%> <%@page import="com.costech.common.helper.AttachmentHelper" %> <%@page import="com.costech.common.bean.Attachment" %> <%@page import="com.costech.common.service.ICommonService"%> <%@page import="com.costech.common.helper.ServiceHelper"%> <%@page import="com.costech.common.constants.CommonConstants"%> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <% request.setCharacterEncoding("utf-8"); String referenceID = StringUtility.toStringValue(request.getParameter("referenceID"),""); ICommonService gd = (ICommonService)ServiceHelper.getService(CommonConstants.COMMON_SERVICE); AttachmentHelper ga = new AttachmentHelper(); String userid = (String)session.getAttribute("userid"); try{ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 1024 * 20);////设置上传工厂的限制 ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * 20);//设置最大的上传限制 List items = upload.parseRequest(request);//处理HTTP请求,items是所有的表单项 for(int i =0; i < items.size(); i ++){ FileItem fileItem=(FileItem)items.get(i); String name = fileItem.getName(); if(name==null || name.trim().length()==0) { continue; } name = name.substring(name.lastIndexOf("\\")+1); String title = name.substring(0,name.lastIndexOf('.')); int size = (int)fileItem.getSize(); String contentType=fileItem.getContentType(); byte[] fileContent=fileItem.get(); Attachment attachment = new Attachment(); attachment.setFileName(name); attachment.setFileContentType(contentType); attachment.setFileSize(size); attachment.setFileContent(fileContent); attachment.setFileTitle(title); attachment.setReferenceID(referenceID); // attachment.setFileType(fileType); attachment.setUploader(userid); String result = ga.update("xt_document",attachment); } }catch(Exception e) { e.printStackTrace(); } String url = request.getHeader("referer"); response.sendRedirect(url); %>
7.3 DeleteFiles.jsp
<%@page import="java.util.*" %> <%@page import="com.costech.common.constants.CommonConstants"%> <%@page import="com.costech.common.service.ICommonService"%> <%@page import="com.costech.common.helper.ServiceHelper"%> <%@page import="com.costech.common.util.StringUtility" %> <%@page import="com.costech.common.util.json.JSONObject"%> <%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% request.setCharacterEncoding("UTF-8"); JSONObject retJson = new JSONObject(); String code = "1"; String msg = "操作成功"; String data = ""; String p_userid = (String)session.getAttribute("userid"); ICommonService gd = (ICommonService)ServiceHelper.getService(CommonConstants.COMMON_SERVICE); String fileIDs = StringUtility.toTrimString(request.getParameter("fileIDs")); Set<String> fileIDsSet = new HashSet<String>(); try{ if(fileIDs!=null && fileIDs.trim().length()>0) { String[] fileIDsArr = fileIDs.split(","); gd.deleteData("XT_Document", "FileID/[@0]", fileIDsArr); } retJson.put("code", code); retJson.put("msg", msg); retJson.put("data", ""); out.write(retJson.toString()); } catch (Exception e) { e.printStackTrace(System.out); code = "0"; msg = e.getMessage(); retJson.put("code", code); retJson.put("msg", msg); retJson.put("data", ""); out.write(retJson.toString()); } %>
7.4 DownloadFiles.jsp
<%@page import="java.util.*" %> <%@page import="com.costech.common.helper.AuthHelper" %> <%@page import="com.costech.common.constants.CommonConstants"%> <%@page import="com.costech.common.service.ICommonService"%> <%@page import="com.costech.common.helper.ServiceHelper"%> <%@page import="com.costech.common.util.StringUtility" %> <%@page import="com.costech.common.bean.Attachment" %> <%@page import="com.costech.common.component.page.VOPager" %> <%@page import="com.costech.common.helper.AttachmentHelper" %> <%@page import="java.io.BufferedInputStream"%> <%@page import="java.io.BufferedOutputStream"%> <%@page import="java.io.File"%> <%@page import="java.io.FileInputStream"%> <%@page import="java.io.FileOutputStream"%> <%@page import="java.io.IOException"%> <%@page import="java.io.InputStream"%> <%@page import="java.io.OutputStream"%> <%@page import="org.apache.commons.compress.archivers.zip.*"%> <%@page import="com.costech.module.hr.chk.util.ContantsAdmin"%> <%@ include file="/include/General.jsp" %> <% String p_userid = (String)session.getAttribute("userid"); ICommonService gd = (ICommonService)ServiceHelper.getService(CommonConstants.COMMON_SERVICE); AttachmentHelper gatt = new AttachmentHelper(); String fileIDs = StringUtility.toTrimString(request.getParameter("fileIDs")); String referenceID = StringUtility.toTrimString(request.getParameter("referenceID")); Set<String> fileIDsSet = new HashSet<String>(); if(fileIDs!=null && fileIDs.trim().length()>0) { String[] fileIDsArr = fileIDs.split(","); for(int i=0;i<fileIDsArr.length;i++) { if(fileIDsArr[i]==null || fileIDsArr[i].trim().length()==0) { continue; } fileIDsSet.add(fileIDsArr[i]); } }else if(referenceID!=null && referenceID.trim().length()>0) { String sql = "select FileID from XT_Document where ReferenceID ='" + referenceID + "'"; List list = gd.getDataList(sql, Attachment.class); for(int i=0;i<list.size();i++) { Attachment att = (Attachment)list.get(i); fileIDsSet.add(att.getFileID()); } }else { return; } try{ if(fileIDsSet.size()==1)//选择一个文件 { String fileID = fileIDsSet.iterator().next(); Attachment att = gatt.getAttachment("XT_Document",fileID); String fileName = new String(att.getFileName().getBytes(),"iso-8859-1"); byte[] context = att.getFileContent(); //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); //2.设置文件头:最后一个参数是设置下载文件名 response.setHeader("Content-Disposition", "attachment;fileName="+fileName); java.io.OutputStream os = response.getOutputStream(); os.write(context); //注意看以下几句的使用 os.flush(); os.close(); response.flushBuffer(); out.clear(); out = pageContext.pushBody(); }else if(fileIDsSet.size()>1)//选择多个文件,则打包下载 { response.reset(); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment;filename=attachment.zip"); java.io.OutputStream os = response.getOutputStream(); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); Iterator<String> it = fileIDsSet.iterator(); while(it.hasNext()) { String fileID = it.next(); Attachment att = gatt.getAttachment("XT_Document",fileID); String fileName = att.getFileName(); String fileTitle = att.getFileTitle(); byte[] context = att.getFileContent(); int fileSize = att.getFileSize(); String strFileSize = ""; if (fileSize > 1024) { strFileSize = fileSize / 1024 + "KB"; } else { strFileSize = fileSize + "Byte"; } ZipArchiveEntry entry = new ZipArchiveEntry(fileName); zos.putArchiveEntry(entry); zos.write(context); zos.closeArchiveEntry(); } zos.flush(); zos.close(); //注意看以下几句的使用 os.flush(); os.close(); response.flushBuffer(); out.clear(); out = pageContext.pushBody(); } } catch (Exception e) { e.printStackTrace(System.out); } finally { } %>