首页 > 代码库 > spring mvc文件上传
spring mvc文件上传
1.配置spring mvc配置文件
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> <property name="maxUploadSize" value="20000000"/> </bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.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>
2.文件上传controller
package com.example.controller;import java.util.Iterator;import javax.servlet.http.HttpServletRequest;import org.springframework.format.datetime.joda.MillisecondInstantPrinter;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.multipart.commons.CommonsMultipartFile;import org.springframework.web.multipart.commons.CommonsMultipartResolver;@Controllerpublic class uploadController { @RequestMapping("upload") public String init(){ return "upload"; } /** * 单文件上传 * @param file * @return */ @RequestMapping("upload_submit") public String submit(@RequestParam CommonsMultipartFile file){ System.out.println(file.getOriginalFilename()); System.out.println(file.getSize()); System.out.println(file.getContentType()); return "hello"; } /** * 多文件上传 * @param request * @return */ @RequestMapping("upload_submit2") public String sumbit2(HttpServletRequest request){ CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext()); if(commonsMultipartResolver.isMultipart(request)){ MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest) request; Iterator<String> iterator=multipartHttpServletRequest.getFileNames(); while(iterator.hasNext()){ MultipartFile multipartFile=multipartHttpServletRequest.getFile(iterator.next()); System.out.println(multipartFile.getOriginalFilename()); } } return "hello"; }}
spring mvc文件上传
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。