您的位置:首页 > 编程语言 > Java开发

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,结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐