spring mvc CommonsMultipartResolver文件上传maxUploadSize限制大小

第一步:配置sping

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--1024*200即200k-->
<property name="maxUploadSize" value="204800"/>
<!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>

第二步:在上传action中自己捕获异常

@RequestMapping
public void execute(
@RequestParam(required = false) MultipartFile file,
@RequestParam(value = "file_info_id", required = false) Integer fileInfoId,
ModelMap model, HttpServletRequest request) throws Exception {

if (file == null || file.isEmpty()) {
return;
}
byte[] bytes = file.getBytes();
……………………
………………
}
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex,HttpServletRequest request) {
Map<Object, Object> model = new HashMap<Object, Object>();
if (ex instanceof MaxUploadSizeExceededException){
model.put("errors", "文件应不大于 "+
getFileKB(((MaxUploadSizeExceededException)ex).getMaxUploadSize()));
} else{
model.put("errors", "不知错误: " + ex.getMessage());
}
return new ModelAndView("/common/file/upload", (Map) model);

}

private String getFileKB(long byteFile){
if(byteFile==0)
return "0KB";
long kb=1024;
return ""+byteFile/kb+"KB";
}
private String getFileMB(long byteFile){
if(byteFile==0)
return "0MB";
long mb=1024*1024;
return ""+byteFile/mb+"MB";
}


第三步:界面

<script type="text/javascript">
$(function() {
$('#frmupload1').submit(function() {
if ($('#file1').val() == '') {
alert('请选择上传导入文件!');
$('#file1').focus();
return false;
}else{
if(!isvalidatefile($('#file1').val()))
return false;

}
});
$('#frmupload2').submit(function() {
if ($('#file2').val() == '') {
alert('请选择上传导入文件!');
$('#file2').focus();
return false;
}else{
if(!isvalidatefile($('#file2').val()))
return false;

}
});
});

function isvalidatefile(obj) {

var extend = obj.substring(obj.lastIndexOf(".") + 1);
//alert(extend);
if (extend == "") {
} else {
if (!(extend == "xls" )) {
alert("请上传后缀名为xls(Excel2003)或xlsx(Excel2007)的文件!");

return false;
}
}
return true;
}
<body>
<h1>上传文件</h1>
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkSubmit();">

<p>请选择文件:</p>

<p ${not empty errors ?"style='color : red;'":""}>${errors}</p>
<input type="file" name="file" id="file"/> <input type="submit" value="确定"/>
</form>
</body>


参考来源:
[url=http://blog.youkuaiyun.com/walkerjong/article/details/7211133]spring MVC上传文件使用了common.fileupload组件[/url]
[url=http://www.open-open.com/home/space-668-do-blog-id-5708.html]使用Spring MVC和注释配置来实现文件上传[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值