首页 > 代码库 > spring mvc CommonsMultipartResolver文件上传maxUploadSize限制大小
spring mvc CommonsMultipartResolver文件上传maxUploadSize限制大小
第一步:配置sping
Xml代码
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!--1024*200即200k-->
- <property name="maxUploadSize" value=http://www.mamicode.com/"204800"/>
- <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
- <property name="resolveLazily" value=http://www.mamicode.com/"true"/>
- </bean>
第二步:在上传action中自己捕获异常
Java代码
- @RequestMapping
- public void execute(
- @RequestParam(required = false) MultipartFile file,
- @RequestParam(value = "file_info_id", required = false) Integer fileInfoId,
- throws Exception {
- if (file == null || file.isEmpty()) {
- return;
- byte[] bytes = file.getBytes();
- ………………
- @ExceptionHandler(Exception.class)
- public ModelAndView handleException(Exception ex,HttpServletRequest request) {
- new HashMap<Object, Object>();
- if (ex instanceof MaxUploadSizeExceededException){
- "errors", "文件应不大于 "+
- } else{
- "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";
- }
第三步:界面
Html代码
- <script type="text/javascript">
- $(‘#frmupload1‘).submit(function() {
- alert(‘请选择上传导入文件!‘);
- return false;
- if(!isvalidatefile($(‘#file1‘).val()))
- });
- if ($(‘#file2‘).val() == ‘‘) {
- $(‘#file2‘).focus();
- }else{
- return false;
- }
- });
- function isvalidatefile(obj) {
- var extend = obj.substring(obj.lastIndexOf(".") + 1);
- if (extend == "") {
- if (!(extend == "xls" )) {
- return false;
- }
- }
- <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=http://www.mamicode.com/"确定"/>
- </form>
- </body>
spring mvc CommonsMultipartResolver文件上传maxUploadSize限制大小
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。