Spring MVC中使用ExtJS上传文件

简介:

文件上传功能是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-image: url(images/icon/add.gif) !important;
             }
                                
             .update {
                 background-image: url(images/icon/update.gif) !important;
             }
                                
             .delete {
                 background-image: url(images/icon/delete.gif) !important;
             }
             .assign {
                 background-image: url(images/icon/list-items.gif) !important;
             }
             .ux-combo-selectall{
                 padding:3px;
             }
             .ux-combo-selectall-icon-checked{
                  transparent  url(ext-3.1.0/resources/images/default/menu/checked.gif);
             }
             .ux-combo-selectall-icon-unchecked {  
                  transparent  url(ext-3.1.0/resources/images/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/images/default/menu/checked.gif);
             }
             .ux-lovcombo-icon-unchecked {
              transparent  url(ext-3.1.0/resources/images/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 = "js/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 = "images/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);*/
                     
     }
                 
}



效果图:


后台效果图:





本文转自 梦朝思夕 51CTO博客,原文链接:http://blog.51cto.com/qiangmzsx/1199686


相关文章
|
1月前
|
JSON 前端开发 Java
SSM:SpringMVC
本文介绍了SpringMVC的依赖配置、请求参数处理、注解开发、JSON处理、拦截器、文件上传下载以及相关注意事项。首先,需要在`pom.xml`中添加必要的依赖,包括Servlet、JSTL、Spring Web MVC等。接着,在`web.xml`中配置DispatcherServlet,并设置Spring MVC的相关配置,如组件扫描、默认Servlet处理器等。然后,通过`@RequestMapping`等注解处理请求参数,使用`@ResponseBody`返回JSON数据。此外,还介绍了如何创建和配置拦截器、文件上传下载的功能,并强调了JSP文件的放置位置,避免404错误。
|
1月前
|
前端开发 Java 应用服务中间件
【Spring】Spring MVC的项目准备和连接建立
【Spring】Spring MVC的项目准备和连接建立
54 2
|
2月前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
1月前
|
XML 前端开发 Java
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
本文阐述了Spring、Spring Boot和Spring MVC的关系与区别,指出Spring是一个轻量级、一站式、模块化的应用程序开发框架,Spring MVC是Spring的一个子框架,专注于Web应用和网络接口开发,而Spring Boot则是对Spring的封装,用于简化Spring应用的开发。
115 0
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
|
2月前
|
XML 缓存 前端开发
springMVC02,restful风格,请求转发和重定向
文章介绍了RESTful风格的基本概念和特点,并展示了如何使用SpringMVC实现RESTful风格的请求处理。同时,文章还讨论了SpringMVC中的请求转发和重定向的实现方式,并通过具体代码示例进行了说明。
springMVC02,restful风格,请求转发和重定向
|
1月前
|
安全 算法 Java
强大!基于Spring Boot 3.3 六种策略识别上传文件类型
【10月更文挑战第1天】在Web开发中,文件上传是一个常见的功能需求。然而,如何确保上传的文件类型符合预期,防止恶意文件入侵,是开发者必须面对的挑战。本文将围绕“基于Spring Boot 3.3 六种策略识别上传文件类型”这一主题,分享一些工作学习中的技术干货,帮助大家提升文件上传的安全性和效率。
46 0
|
3月前
|
Java 数据库连接 Spring
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
文章是关于Spring、SpringMVC、Mybatis三个后端框架的超详细入门教程,包括基础知识讲解、代码案例及SSM框架整合的实战应用,旨在帮助读者全面理解并掌握这些框架的使用。
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
|
3月前
|
XML JSON 数据库
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
这篇文章详细介绍了RESTful的概念、实现方式,以及如何在SpringMVC中使用HiddenHttpMethodFilter来处理PUT和DELETE请求,并通过具体代码案例分析了RESTful的使用。
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
|
2月前
|
Java API 开发者
【已解决】Spring Cloud Feign 上传文件,提示:the request was rejected because no multipart boundary was found的问题
【已解决】Spring Cloud Feign 上传文件,提示:the request was rejected because no multipart boundary was found的问题
402 0
|
3月前
|
前端开发 应用服务中间件 数据库
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查
这篇文章通过一个具体的项目案例,详细讲解了如何使用SpringMVC、Thymeleaf、Bootstrap以及RESTful风格接口来实现员工信息的增删改查功能。文章提供了项目结构、配置文件、控制器、数据访问对象、实体类和前端页面的完整源码,并展示了实现效果的截图。项目的目的是锻炼使用RESTful风格的接口开发,虽然数据是假数据并未连接数据库,但提供了一个很好的实践机会。文章最后强调了这一章节主要是为了练习RESTful,其他方面暂不考虑。
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查