首页 > 代码库 > 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文件上传