文件上传功能是Web开中,不可或缺的功能。
本博文主要讲解在Spring MVC使用ExtJS进行文件的上传。
/mzsxBlog/src/config/springmvc.xml
这是SpringMVC的配置文件,文件上传的配置如下:
1 2 3 4 5 6 7 | <!-- 文件上传 --> < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > < property name = "maxUploadSize" value = "10240000" /> < property name = "resolveLazily" value = "true" /> < property name = "maxInMemorySize" value = "4096" /> </ bean > |
前台JSP如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | <%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html > < head > <% String contextPath = request.getContextPath(); %> < title >应用管理</ title > <%@ include file="/js/_scripts.jsp"%> < style type = "text/css" > .textfield-red { color: #FF0000; } </ style > <!-- 字体红色的样式--> < STYLE TYPE = "text/css" > #content { width: 100%; height: 100%; } .add { background-p_w_picpath: url(p_w_picpaths/icon/add.gif) !important; } .update { background-p_w_picpath: url(p_w_picpaths/icon/update.gif) !important; } .delete { background-p_w_picpath: url(p_w_picpaths/icon/delete.gif) !important; } .assign { background-p_w_picpath: url(p_w_picpaths/icon/list-items.gif) !important; } .ux-combo-selectall{ padding:3px; } .ux-combo-selectall-icon-checked{ transparent url(ext-3.1.0/resources/p_w_picpaths/default/menu/checked.gif); } .ux-combo-selectall-icon-unchecked { transparent url(ext-3.1.0/resources/p_w_picpaths/default/menu/unchecked.gif); } .ux-combo-selectall-icon { text-indent:1.8em; background-position: 3px 2px ! important; background-repeat:no-repeat ! important; height:22px; line-height:20px; font-size:12px; font-weight:bold; -moz-user-select:none; } .ux-lovcombo-icon { width:16px; height:16px; float:left; background-position: -1px -1px ! important; background-repeat:no-repeat ! important; } .ux-lovcombo-icon-checked { transparent url(ext-3.1.0/resources/p_w_picpaths/default/menu/checked.gif); } .ux-lovcombo-icon-unchecked { transparent url(ext-3.1.0/resources/p_w_picpaths/default/menu/unchecked.gif); } /* IE patch */ .ext-ie .ux-lovcombo-item-text { position:absolute; left:16px; top:3px; } .ext-ie .ux-lovcombo-icon { float:none; } .ext-ie .x-combo-list-item { position:relative; } </ STYLE > < link href = "ext-3.1.0/ux/css/Spinner.css" type = "text/css" rel = "stylesheet" /> < script type = "text/javascript" src = "ext-3.1.0/ux/DateTime.js" ></ script > < script type = "text/javascript" src = "ext-3.1.0/ux/SpinnerField.js" ></ script > < script type = "text/javascript" src = "ext-3.1.0/ux/Spinner.js" ></ script > < script type = "text/javascript" src=\'#\'" /Ext.ux.form.LovCombo.js"></ script > < script type = "text/javascript" src = "ext-3.1.0/ux/fileuploadfield/FileUploadField.js" ></ script > < script type = "text/javascript" > Ext.onReady(function() { Ext.QuickTips.init(); var excelUpload = new Ext.form.TextField({ id:'upload', anchor:'90%', height:30, width:350, name:'userfile', inputType:'file', fieldLabel:'文件选择' }); var formPanel = new Ext.form.FormPanel({ labelWidth:80, bodyStyle:'padding:5 5 5 5', height:515, width:200, frame:true, fileUpload:true, items:[excelUpload] }); // 定义按钮 var upLoadFile = new Ext.Toolbar.Button({ text:'上传' }); // 上传数据功能 var up = function(bt) { var filepath = Ext.getCmp('upload').getRawValue();// 上传文件名称的路径 var suffix = filepath.substring(filepath.lastIndexOf('.') + 1, filepath.length); if (filepath == ""){ Ext.Msg.show({title:'提示',msg:'请选择文件!',buttons:Ext.Msg.OK,icon:Ext.MessageBox.INFOR}); return; } else { var array = new Array(); array = filepath.split("\\"); var length = array.length; var fileName = ""; var index = 0; for (index = 0; index < length ; index++) { if (fileName == "") { fileName = array [index]; } else { fileName = fileName + "/" + array[index]; } } formPanel.getForm().submit({ url:'file.sp? method = upload ', method:'POST', waitMsg:'数据上传中, 请稍等...', success:function(form, action) { if(action.result.success == true){ Ext.MessageBox.alert("提示信息","文件上传成功!!!"); } }, failure : function(form, action) { Ext.MessageBox.alert("提示信息","请求失败,文件上传失败"); } }); } } // 添加按钮的响应事件 upLoadFile.addListener('click', up, false); var window = new Ext.Window({ title:'上传文件', width:500, height:200, minWidth:500, minHeight:200, layout:'fit', plain:true, modal:true, //closeAction:'hide', bodyStyle:'padding:5px;', buttonAlign:'center', items:formPanel, buttons:[upLoadFile] }); window.show(); }); </script> </ head > < body > < div id = "Layer1" style = "position:absolute; width:100%; height:100%; z-index:-1" > < img src=\'#\'" /file.jpg" height = "100%" width = "100%" /> < div id = "form" ></ div > </ div > </ body > </ html > |
后台的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | package com.mzsx.flie.contorller; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import com.mzsx.admin.contorller.AdminContorller; import com.mzsx.flie.service.FileService; import com.mzsx.model.Admin; import com.mzsx.model.FileLoading; @Controller @RequestMapping ( "file.sp" ) public class FileContorller { @Autowired private FileService fileService; private static Logger logger = Logger.getLogger(AdminContorller. class ); @RequestMapping (params = "method=upload" , method = RequestMethod.POST) public void addFileUp(HttpServletRequest request,HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); FileLoading fileUp = new FileLoading(); //获取用户 Admin admin = (Admin) request.getSession().getAttribute( "admin" ); int userid = admin.getId(); //用户ID Date createdTime = new Date(); //使用MultipartHttpServletRequest包装文件数据 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; //目录命名格式如:*files2013-03-05-22 SimpleDateFormat dateformat = new SimpleDateFormat( "yyyy-MM-dd" ); //构建图片保存的目录 String logoPathDir = "/upload/file" + dateformat.format( new Date()); //得到图片保存目录的真实路径 String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir); //根据真实路径创建目录 File logoSaveFile = new File(logoRealPathDir); if (!logoSaveFile.exists()) logoSaveFile.mkdirs(); //页面控件的文件流 MultipartFile multipartFile = multipartRequest.getFile( "userfile" ); // 获取文件名/ String filename = multipartFile.getOriginalFilename(); fileUp.setFileOldName(filename); long time = createdTime.getTime(); // 时间 int index = filename.lastIndexOf( "." ); if (index == - 1 ) { filename = filename + "-" + time; // 文件名 logger.info( "文件名:" +filename); } else { filename = filename.substring( 0 , index) + "-" + time + filename.substring(index); logger.info( "文件名:" +filename); } //设置属性值 fileUp.setUserid(userid); fileUp.setFileNewName(filename); fileUp.setPath(logoRealPathDir); fileUp.setStatus( 1 ); //拼成完整的文件保存路径加文件 String fileName = logoRealPathDir + File.separator + filename; File file = new File(fileName); try { //保存上传文件 multipartFile.transferTo(file); logger.info(filename+ "上传成功!!!" ); try { //插入数据库 fileService.insertFile(fileUp); map.put( "success" , "true" ); } catch (Exception e) { // TODO: handle exception map.put( "success" , "false" ); logger.error( "异常出现:" +e); } /*String json = "{success: true}"; response.setContentType("text/html; charset=UTF-8"); response.getWriter().write(json); response.flushBuffer();*/ /*Map<String, Object> result = new HashMap<String, Object>(0); result.put("success", true); response.setContentType("text/html"); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getOutputStream(), result);*/ response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("{success:true}"); } catch (IllegalStateException e) { logger.error("异常出现:"+e); } catch (IOException e) { logger.error("异常出现:"+e); } //response.setContentType("text/html; charset=UTF-8"); //response.setContentType("application/json; charset=utf-8"); //return new ModelAndView("jsonView", map); /*String json="{success : true}"; HttpHeaders reHeaders=new HttpHeaders(); reHeaders.setContentType(MediaType.TEXT_HTML); return new ResponseEntity<String>(json,reHeaders,HttpStatus.OK);*/ } } |
效果图:
后台效果图: