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


相关文章
|
5月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
前端开发 Java 测试技术
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
694 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
1317 0
|
前端开发 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
772 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = &quot;/test&quot;, produces = &quot;application/json; charset=UTF-8&quot;)`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
694 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
493 0
|
8月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
586 0
|
8月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
236 0
|
8月前
|
JSON 前端开发 Java
第05课:Spring Boot中的MVC支持
第05课:Spring Boot中的MVC支持
351 0
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
810 29