SpringMVC+EXTJS4.1上传文件,并通过JSON格式返回异常信息
2014-04-12 13:18
471 查看
1.配置SpringMVC,如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
xmlns="http://www.springframework.org/schema/beans">
<!--注解支持 -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!--注解扫描的包 -->
<context:component-scan base-package="com.kedacom.ycyl.web.controller" />
<!--jsp页面文件路径前缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jspView/" p:suffix=".jsp" />
<!--配置接收文件类型的Resolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为20MB -->
<!-- <property name="maxUploadSize" value="20971520" /> -->
<property name="maxUploadSize" value="524288" />
<property name="defaultEncoding" value="utf-8" />
<property name="maxInMemorySize" value="4096"/>
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
</props>
</property>
</bean>
<!--XML与Object转换的功能类 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/xml;charset=UTF-8</value>
<value>multipart/form-data</value>
<value>*/*</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>
</beans>
2.编写Controller类
@RequestMapping(value = "/add2", method = RequestMethod.POST)
@ResponseBody
public JsonResult addMcu2(DefaultMultipartHttpServletRequest request, String id, String name, String ipAddress, String confercenterId){
JsonResult jsResult = new JsonResult() ;
System.out.println("name is : " + name);//收集参数,处理业务。
try {
String uploadDir = request.getRealPath("/")+"upload";
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
MultipartFile file = (MultipartFile) request.getFile("file") ;
String originalFileName = file.getOriginalFilename();
logger.debug("上传的文件名称为:"+ originalFileName);
String fileName = originalFileName.substring(0, originalFileName.lastIndexOf(".")) ;
String fileType = originalFileName.substring(originalFileName.lastIndexOf(".")) ;
String sep = System.getProperty("file.separator");
File uploadedFile = new File(uploadDir + sep + fileName+DateUtil.getNowDateString()+fileType);
byte[] bytes = file.getBytes();
FileCopyUtils.copy(bytes, uploadedFile);
} catch (IOException e) {
jsResult.setErrorMsg("上传文件出现异常!") ;
logger.error("[addMcu2]上传文件出现异常:" + e.getMessage()) ;
e.printStackTrace();
}
jsResult.setMsg("保存MUC信息和上传附件成功") ;
return jsResult ;
}
3.编写error_fileupload.jsp文件
<%@ page contentType="application/json;charset=UTF-8" pageEncoding="UTF-8"%>
{"msg":"文件大小超过512KB"}
error_fileupload.jsp的文件内容只有这些。
4.ExtJS界面代码
Ext.define('VCR.view.form.MCU',{
extend:'Ext.form.Panel',
alias:'widget.mcuform',
initComponent:function()
{
Ext.apply(this,{
width: 400,
bodyPadding: 15,
waitMsgTarget: true,
jsonSubmit:true,
fieldDefaults: {
labelAlign: 'left',
anchor:'98%',
blankText:'不能为空',
msgTarget: 'side'
},
items:[{
xtype: 'hiddenfield',
name: 'id',
value :this.mcuId || ''
},{
xtype: 'hiddenfield',
name: 'confercenterId',
value :this.zoneId || -1,
allowBlank:false
},{
xtype: 'textfield',
value :this.zoneName || ' ',
fieldLabel: '所属中心',
readOnly:true,
disabled:true
},{
xtype: 'textfield',
name: 'name',
value : this.mcuName || '',
fieldLabel: 'MCU名称',
allowBlank:false
},{
xtype: 'textfield',
name: 'ipAddress',
value :this.mcuIp || '',
fieldLabel: '网络地址',
vtype:'IPAddress',
allowBlank:false
},{
xtype: 'filefield',
emptyText : '选择文件存放路径',
name: 'file',
fieldLabel: '附件',
buttonText : '选择文件'
}],
buttons: [{
text: this.mcuId ? '修改' : '提交',
scope:this,
handler:function(){
var url = this.mcuId ? 'rest/mcu/update' : 'rest/mcu/add2' ;
this.getForm().submit({
url: url,
submitEmptyText: false,
waitMsg: '正在提交...',
waitTitle: '请等待',
scope:this,
success: function(form, action) {
if(this.successCallback){
this.successCallback.call(this,action.result);
};
Ext.Msg.alert('提示', action.result.msg);
},
failure:function(form, action) {
Ext.Msg.alert('提示', action.result.msg);
}
});
}
},{
text: '重置',
scope:this,//不加,this.getForm()就无法调用
handler:function(){this.getForm().reset();}
}]
});
this.callParent();
}
});
5.运行实际效果截图:
a)正常的文件上传,选择了桌面上的一张.jpg的图片,大小为:436KB 在上传的大小限制内
点击提交,结果如下图:
后台打印了MCU名称
项目路径下被上传的文件:
b)上传超过限制的文件
该PDF文件大小为:36.8M
点击提交结果:
OK,结束。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
xmlns="http://www.springframework.org/schema/beans">
<!--注解支持 -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!--注解扫描的包 -->
<context:component-scan base-package="com.kedacom.ycyl.web.controller" />
<!--jsp页面文件路径前缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jspView/" p:suffix=".jsp" />
<!--配置接收文件类型的Resolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为20MB -->
<!-- <property name="maxUploadSize" value="20971520" /> -->
<property name="maxUploadSize" value="524288" />
<property name="defaultEncoding" value="utf-8" />
<property name="maxInMemorySize" value="4096"/>
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
</props>
</property>
</bean>
<!--XML与Object转换的功能类 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/xml;charset=UTF-8</value>
<value>multipart/form-data</value>
<value>*/*</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>
</beans>
2.编写Controller类
@RequestMapping(value = "/add2", method = RequestMethod.POST)
@ResponseBody
public JsonResult addMcu2(DefaultMultipartHttpServletRequest request, String id, String name, String ipAddress, String confercenterId){
JsonResult jsResult = new JsonResult() ;
System.out.println("name is : " + name);//收集参数,处理业务。
try {
String uploadDir = request.getRealPath("/")+"upload";
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
MultipartFile file = (MultipartFile) request.getFile("file") ;
String originalFileName = file.getOriginalFilename();
logger.debug("上传的文件名称为:"+ originalFileName);
String fileName = originalFileName.substring(0, originalFileName.lastIndexOf(".")) ;
String fileType = originalFileName.substring(originalFileName.lastIndexOf(".")) ;
String sep = System.getProperty("file.separator");
File uploadedFile = new File(uploadDir + sep + fileName+DateUtil.getNowDateString()+fileType);
byte[] bytes = file.getBytes();
FileCopyUtils.copy(bytes, uploadedFile);
} catch (IOException e) {
jsResult.setErrorMsg("上传文件出现异常!") ;
logger.error("[addMcu2]上传文件出现异常:" + e.getMessage()) ;
e.printStackTrace();
}
jsResult.setMsg("保存MUC信息和上传附件成功") ;
return jsResult ;
}
3.编写error_fileupload.jsp文件
<%@ page contentType="application/json;charset=UTF-8" pageEncoding="UTF-8"%>
{"msg":"文件大小超过512KB"}
error_fileupload.jsp的文件内容只有这些。
4.ExtJS界面代码
Ext.define('VCR.view.form.MCU',{
extend:'Ext.form.Panel',
alias:'widget.mcuform',
initComponent:function()
{
Ext.apply(this,{
width: 400,
bodyPadding: 15,
waitMsgTarget: true,
jsonSubmit:true,
fieldDefaults: {
labelAlign: 'left',
anchor:'98%',
blankText:'不能为空',
msgTarget: 'side'
},
items:[{
xtype: 'hiddenfield',
name: 'id',
value :this.mcuId || ''
},{
xtype: 'hiddenfield',
name: 'confercenterId',
value :this.zoneId || -1,
allowBlank:false
},{
xtype: 'textfield',
value :this.zoneName || ' ',
fieldLabel: '所属中心',
readOnly:true,
disabled:true
},{
xtype: 'textfield',
name: 'name',
value : this.mcuName || '',
fieldLabel: 'MCU名称',
allowBlank:false
},{
xtype: 'textfield',
name: 'ipAddress',
value :this.mcuIp || '',
fieldLabel: '网络地址',
vtype:'IPAddress',
allowBlank:false
},{
xtype: 'filefield',
emptyText : '选择文件存放路径',
name: 'file',
fieldLabel: '附件',
buttonText : '选择文件'
}],
buttons: [{
text: this.mcuId ? '修改' : '提交',
scope:this,
handler:function(){
var url = this.mcuId ? 'rest/mcu/update' : 'rest/mcu/add2' ;
this.getForm().submit({
url: url,
submitEmptyText: false,
waitMsg: '正在提交...',
waitTitle: '请等待',
scope:this,
success: function(form, action) {
if(this.successCallback){
this.successCallback.call(this,action.result);
};
Ext.Msg.alert('提示', action.result.msg);
},
failure:function(form, action) {
Ext.Msg.alert('提示', action.result.msg);
}
});
}
},{
text: '重置',
scope:this,//不加,this.getForm()就无法调用
handler:function(){this.getForm().reset();}
}]
});
this.callParent();
}
});
5.运行实际效果截图:
a)正常的文件上传,选择了桌面上的一张.jpg的图片,大小为:436KB 在上传的大小限制内
点击提交,结果如下图:
后台打印了MCU名称
项目路径下被上传的文件:
b)上传超过限制的文件
该PDF文件大小为:36.8M
点击提交结果:
OK,结束。
相关文章推荐
- ssh三层框架——上传文件(大小格式筛选+json返回相对地址)
- ie8下使用jquery-file-upload上传文件后返回json格式数据提示下载
- struts2 + ajax(由前台的form提交数据到后台,再根据form所调用返回获取的后台json格式的数据返回到前端,然后前端用jquery对json数据进行解析)==》》涉及文件上传的部分
- PHP读取目录下所有文件,并通过ajax返回json格式的数据
- ASP.NET MVC上传文件成功返回Json格式数据弹出下载框解决方案
- 一个完整的通过encoding/json信息传递格式,采用http.POST利用进行与服务器通信,并对返回结果进行解析处理的典型案例
- 使用jquery uploadfy插件上传文件返回json格式的处理办法
- 关于ext与springMVC中上传文件并以JSON格式返回入STORE的问题
- 上传文件时出现 不支持给定路径的格式..异常信息
- RxJava + Retrofit+okhttp 封装,包含对相同格式请求数据、相同格式返回数据处理,显示 Material Design 加载 dialog,文件上传下载进度展示、全局异常捕捉。
- JDBC- exercise-2 通过htttp 访问 数据库,返回一个JSON格式的相应信息
- spring接口通过配置支持返回多种格式(xml,json,html,excel)
- Ajax 上传文件,返回JSON字符串在FireFox下解析带有<pre>标签的解决办法
- Spring MVC框架文件上传返回JSON在IE浏览器中提示下载解决方法
- 上传文件返回的json数据会被提示下载问题解决方案
- Jfinal Ajax上传文件 接受JSON返回值
- JavaWeb框架-SpringMVC-4-文件上传与返回JSON数据
- 文件上传 通过隐藏iframe的方式来实现ajax上传文件并返回处理结果 ie乱码问题解决
- Ajax 上传文件返回JSON字符串FireFox解析出来后带有<pre>标签解决办法
- jquery ajaxform上传文件返回不提示信息的问题