用户添加页面有一个“上传”按钮,点击按钮弹出上传界面,上传完成后关闭上传界面。
commons.fileupload-1.2.0.jar、commons.logging-1.1.1.jar、commons.beanutils-1.8.0.jar、commons.collections-3.2.0.jar、commons.io-1.4.0.jar、commons.lang-2.1.0.jar
首先编写核心代码,Javascript打开上传页面,并且从上传页获取返回参数,最后数据返回给回调函数callback:
- function openUpload(functionId,fileType,maxSize,callback){
- var url = root+"/CommonController.jhtml?method=goFileUpload&";
- if(functionId!=null){
- url = url + "functionId="+functionId+"&";
- }
- if(fileType!=null){
- url = url + "fileType="+fileType+"&";
- }
- if(maxSize!=null){
- url = url + "maxSize="+maxSize;
- }
- var win = window.showModalDialog(url,"","dialogWidth:300px;dialogHeight:150px;scroll:no;status:no");
- if(win != null){
- var arrWin = win.split(",");
- callback(arrWin[0],arrWin[1],arrWin[2]);
- }
- }
用户添加页面相关代码,点击“上传”按钮时调用上面的核心js代码,并且获取返回值
- <script>
- .......
-
- function openUpload_(){
- openUpload(null,‘JPG,GIF,JPEG,PNG‘,‘5‘,callback);
- }
-
- /**
- * 回调函数,获取上传文件信息
- * realName真实文件名
- * saveName文件保存名
- * maxSize文件实际大小
- */
- function callback(realName,saveName,maxSize){
- $("#photo_").val(saveName);
- //回调后其它操作
- }
- </script>
-
- <tr>
- <td>头像:</td>
- <td>
- <input type="hidden" name="photo" id="photo_"></input>
- <input type="button" onclick="openUpload_()" value="上传"/>
- </td>
- </tr>
文件上传的JSP代码,需要注意的是在head标签内添加<base target="_self">以防止页面跳转时弹出新窗口,用户选择指定文件,点击上传时就提交表单访问指定后台代码
- <%@ include file="/WEB-INF/jsp/header.jsp" %>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <meta http-equiv="pragma" content="no-cache" />
- <base target="_self">
- <title>文件上传</title>
- </head>
- <body>
- <h5>文件上传</h5><hr/>
- <form id="file_upload_id" name="file_upload_name" action="<%=root%>/CommonController.jhtml?method=doFileUpload" method="post" enctype="multipart/form-data">
- <input type="hidden" name="functionId" value="${functionId}"/>
- <input type="hidden" name="fileType" value="${fileType}"/>
- <input type="hidden" name="maxSize" value="${maxSize}"/>
- <div><input type="file" name="file_upload"/></div>
- <c:if test="${maxSize!=null}">
- <div style="font: 12">文件最大不能超过${maxSize}MB</div>
- </c:if>
- <c:if test="${fileType!=null}">
- <div style="font: 12">文件格式必须是:${fileType}</div>
- </c:if>
- <div><input type="submit" value="上传"/></div>
- </form>
- </body>
- </html>
CommonController目前有两个方法,一个是跳转到上传页面的方法,一个是执行上传操作的方法doFileUpload,上传方法运行的大概逻辑是:首先获取页面的请求参数,fileType用于限制上传文件格式,
maxSize用于限制上传文件最大值,随后创建上传目录上传即可。
- public class CommonController extends BaseController {
- Log log = LogFactory.getLog(CommonController.class);
-
- Properties fileUploadPro = null;
- public CommonController(){
- fileUploadPro = PropertiesUtil.getPropertiesByClass("fileupload.properties");
- }
-
-
- @Override
- public ModeAndView init(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
-
- return null;
- }
-
-
- public ModeAndView goFileUpload(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- String functionId = request.getParameter("functionId");
- String fileType = request.getParameter("fileType");
- String maxSize = request.getParameter("maxSize");
- ModeAndView mav = new ModeAndView("/WEB-INF/jsp/common/fileUpload.jsp");
-
- if(functionId!=null && !"".equals(functionId.trim())){
- mav.addObject("functionId", functionId);
- }
- if(fileType!=null && !"".equals(fileType.trim())){
- mav.addObject("fileType", fileType);
- }
- if(maxSize!=null && !"".equals(maxSize.trim())){
- mav.addObject("maxSize", maxSize);
- }
- return mav;
- }
-
-
- @SuppressWarnings("unchecked")
- public ModeAndView doFileUpload(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
-
- String functionId = request.getParameter("functionId");
- String fileType = request.getParameter("fileType");
- String maxSize = request.getParameter("maxSize");
-
-
- String tempPath = fileUploadPro.getProperty("tempPath");
-
- String filePath = fileUploadPro.getProperty("filePath");
-
- FileUtil.createFolder(tempPath);
- FileUtil.createFolder(filePath);
-
- DiskFileItemFactory factory = new DiskFileItemFactory();
-
- factory.setSizeThreshold(5*1024);
-
- factory.setRepository(new File(tempPath));
- ServletFileUpload upload = new ServletFileUpload(factory);
- if(maxSize!=null && !"".equals(maxSize.trim())){
-
- upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);
- }
-
- try {
-
- List<FileItem> items = upload.parseRequest(request);
- for (FileItem item : items) {
- if(!item.isFormField()){
-
- String fileName = item.getName();
-
-
- String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
- if(fileType!=null && !"".equals(fileType.trim())){
- boolean isRealType = false;
- String[] arrType = fileType.split(",");
- for (String str : arrType) {
- if(fileEnd.equals(str.toLowerCase())){
- isRealType = true;
- break;
- }
- }
- if(!isRealType){
-
- super.printJsMsgBack(response, "文件格式不正确!");
- return null;
- }
- }
-
-
- String uuid = UUID.randomUUID().toString();
-
- StringBuffer sbRealPath = new StringBuffer();
- sbRealPath.append(filePath).append(uuid).append(".").append(fileEnd);
-
- File file = new File(sbRealPath.toString());
- item.write(file);
-
- StringBuffer sb = new StringBuffer();
- sb.append("window.returnValue=‘").append(fileName).append(",").append(uuid).append(".").append(fileEnd).append(",").append(file.length()).append("‘;");
- sb.append("window.close();");
- super.printJsMsg(response, sb.toString());
- log.info("上传文件成功,JS信息:"+sb.toString());
- }
- }
-
- }catch (Exception e) {
-
- super.printJsMsgBack(response, "上传失败,文件大小不能超过"+maxSize+"M!");
- log.error("上传文件异常!",e);
- return null;
- }
-
- return null;
- }
- }
至此一个文件上传即已实现,而且能够基本满足不同模块的上传通用性,我还留着个functionId参数用于以后针对不同模块上传文件到不同目录。