您的位置:首页 > 运维架构 > Tomcat

tomcat7容器下Spring4.x限制上传文件大小问题处理

2015-06-10 00:00 591 查看
摘要: controller层拦截spring上传文件超出设定大小的异常,并且处理tomcat在超出文件大小时导致ERR_CONNECTION_RESET异常的问题。

环境:
apache-tomcat-7.0.59+JAVA7+spring4.0.5

spring xml配置

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="${file_size}"></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="resolveLazily" value="true"></property>
</bean>

注意:resolveLazily为true的意思为文件超出限制后,异常在controller层报出,如果不配置的话,必须用exceptionResolver的方式才能捕获到异常。

controller层处理拦截并处理异常代码:

@ExceptionHandler(MaxUploadSizeExceededException.class)
public
@ResponseBody
String handleException(Exception ex, HttpServletRequest request) throws Exception {
ResponseResult<Object> result = new ResponseResult<Object>(FAILED, "文件超出大小限制!");
return mapper.writeValueAsString(result);
}

以上内容来自于网络,但我测试的时候,html使用ajaxFileUpload提交后始终进入error回调,而不是预期的success回调,导致页面无法提示文件过大的提示。

$.ajaxFileUpload({
url: 'api/user/getImageWidthAndHeight',
secureuri: false,
type: 'POST',
fileElementId: 'headImag',
dataType: 'json',
success: function (data, status) {
...
}, error: function () {
alert("图片处理失败,请重新选择!");
}
});

通过chrome断点调试发现有“net::ERR_CONNECTION_RESET”报错,网上搜索了一下,原来tomcat7|8有上传大小的限制,超过默认文件大小将断开链接,具体的配置项和说明如下:

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" maxSwallowSize="209715200"/>

对,就是maxSwallowSize,默认是坑爹的2097152=2MB。

maxSwallowSize:The maximum number of request body bytes (excluding transfer encoding overhead) that will be swallowed by Tomcat for an aborted upload. An aborted upload is when Tomcat knows that the request body is going to be ignored but the client still sends it. If Tomcat does not swallow the body the client is unlikely to see the response. If not specified the default of 2097152 (2 megabytes) will be used. A value of less than zero indicates that no limit should be enforced.

参见tomcat官方配置说明:http://tomcat.apache.org/tomcat-8.0-doc/config/http.html 中的maxSwallowSize
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息