SpringMVC中使用CommonsMultipartResolver进行文件上传

概述:

CommonsMultipartResolver是基于Apache的Commons FileUpload来实现文件上传功能的。所以在项目中需要相应的jar文件。

FileUpload版本要求1.2及以上。相应的gradle配置:

"commons-fileupload:commons-fileupload:1.2.2"
  • 1

上传方法的实现

1. 代码方式

直接在controler中new一个CommonsMultipartResolver。

@Controller
@RequestMapping(value = "/file")
public class FileController {

    @RequestMapping(value = "/commUploadA")
    @ResponseBody
    public JSONObject commUploadA(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        json.put("succ", false);
        try {
            //直接new一个CommonsMultipartResolver
            CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext());
            cmr.setDefaultEncoding("utf-8");
            cmr.setMaxInMemorySize(40960);
            cmr.setMaxUploadSize(10485760000L);
            if (cmr.isMultipart(request)) {
                MultipartHttpServletRequest multipartRequest = cmr.resolveMultipart(request);
                MultipartFile file = multipartRequest.getFile("uploadFile");// 与页面input的name相同
                File imageFile = new File("d:/upload1.jpg");// 上传后的文件保存目录及名字
                file.transferTo(imageFile);// 将上传文件保存到相应位置
                json.put("succ", true);
                return json;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

}

2. Xml方式

通过spring配置一个名为”multipartResolver”的bean。

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"></property>
    <property name="maxUploadSize" value="10485760000"></property>
    <property name="maxInMemorySize" value="40960"></property>
</bean>

controller中的方法做相应修改。

@Controller
@RequestMapping(value = "/file")
public class FileController {

    @RequestMapping(value = "/commUploadB")
    @ResponseBody
    public JSONObject commUploadB(MultipartHttpServletRequest request) {//参数类型不同
        JSONObject json = new JSONObject();
        json.put("succ", false);
        try {
            MultipartFile file = request.getFile("uploadFile");// 与页面input的name相同
            File imageFile = new File("d:/upload2.jpg");// 上传后的文件保存目录及名字
            file.transferTo(imageFile);// 将上传文件保存到相应位置
            json.put("succ", true);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            return json;
        }
    }
}

 

 

两种方法的区别:

  1. 将CommonsMultipartResolver的实例化由代码实现改为了xml配置实现。
  2. 方法中的参数类型由HttpServletRequest变为了MultipartHttpServletRequest。

而上传的获取和保存逻辑没有变化。

注意:

在使用xml方式时,bean的名字必须为:multipartResolver。可在org.springframework.web.servlet.DispatcherServlet中找到原因:

public class DispatcherServlet extends FrameworkServlet {

    /** Well-known name for the MultipartResolver object in the bean factory for this namespace. */
    public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";

    ......
    /**
     * Initialize the MultipartResolver used by this class.
     * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
     * no multipart handling is provided.
     */
    private void initMultipartResolver(ApplicationContext context) {
        try {
            this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
            if (logger.isDebugEnabled()) {
                logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
            }
        }
        catch (NoSuchBeanDefinitionException ex) {
            // Default is no multipart resolver.
            this.multipartResolver = null;
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
                        "': no multipart request handling provided");
            }
        }
    }
    ......
}

简要分析CommonsMultipartResolver

CommonsMultipartResolver实现接口org.springframework.web.multipart.MultipartResolver,主要作用是将HttpSerlvetRequest封装成MultipartHttpServletRequest。

public interface MultipartResolver {
    ......
    MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException;
    ......
}

具体的封装方法参考CommonsMultipartResolver对resolveMultipart的实现:

org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(javax.servlet.http.Ht
posted @ 2018-02-06 11:52  小学生II  阅读(2045)  评论(0编辑  收藏  举报