• SpringMVC学习指南【笔记7】上传文件


    Spring MVC中处理已上传文件的两种方法,一是利用CommonsFileUpload元件,二是利用Servlet3本地文件上传特性。

    客户端编程

    为了上传文件,必须将html表格的enctype属性值设为multipart/form-data

    <form action="action" enctype="multipart/form-data" method="post">
        select a file<input type="file" name="fieldName" /><!--这个input标签会显示成一个按钮,点击时,会打开一个对话框,用来选择文件-->
        <input type="submit" value="upload" />
    </form>
    <!--上传多个文件,以下3行代码都可以-->
    <input type="file" name="fieldName" multiple />
    <input type="file" name="fieldName" multiple="multiple" />
    <input type="file" name="fieldName" multiple="" />

    MultipartFile接口

    org.springframework.web.multipart.MultipartFile

    例如,Product这个实体类要添加多个文件的属性,List<MultipartFile>  files;

      @RequestMapping(value="product_save")
        public String productSave(HttpServletRequest servletRequest, @ModelAttribute Product product, BindingResult bindingResult,Model model){
            List<MultipartFile> files = product.getFiles();
            List<String> filesName = new ArrayList<String>();
            if(null != files && files.size() > 0){
                for(MultipartFile multipartFile : files){
                    String fileName = multipartFile.getOriginalFilename();
                    filesName.add(fileName);
                    File file = new File(servletRequest.getServletContext().getRealPath("/file"), fileName);
                    try {
                        multipartFile.transferTo(file);        // 保存已上传文件
                    } catch (IllegalStateException | IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            // save product here
            model.addAttribute("product", product);
            return "productDetails";
        }

    JSP页面

    <form:form commandName="product" action="product_save" method="post" enctype="multipart/form-data">
        <fieldset>
            <p>
                <label for="name">product name:</label>
                <form:input id="name" path="name" cssErrorClass="error" />
                <form:errors path="name" cssErrorClass="error" />
            </p>
            <p>
                <label for="file">product file:</label>
                <input type="file" name="files[0]" />
            </p>
        </fieldset>
    </form:form>

    处理已上传的文件的两种方法

    第一种:利用Common FileUpload元件

    Spring MVC的配置文件,这里multipartResolver引用的是CommonMultipartResolver

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/springcontext.xsd
        ">
    
        <!-- 扫描目标包中的类 -->
        <context:component-scan base-package="com.xsl.controller" />
        <context:component-scan base-package="com.xsl.service" />
        
        <!-- 注册用于支持基于注解的控制器的请求处理方法的bean对象 -->
        <mvc:annotation-driven />
        
        <!-- 指示Spring MVC哪些静态资源需要单独处理,不需要dispatcher servlet -->
        <mvc:resources mapping="/css/**" location="/css/" />
        <mvc:resources mapping="/*.html" location="/" />
        <mvc:resources mapping="/image/**" location="/image/" />
    
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
        </bean>
        
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="basename" value="/WEB-INF/resource/messages" />
        </bean>
        
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonMultipartResolver">
        </bean>
    
    </beans>

    第二种:利用Servlet3本地文件上传特性

    给部署描述符(web.xml)中的servlet声明赋值,使一个Servlet变成一个MultipartConfig Servlet,以下代码与用@MultipartConfig给DispatcherServlet进行标注的效果一样,关键是multipart-config这个元素

    <?xml version="1.0" encoding="UTF-8" ?>
    <web-app version="3.0"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
        
        <servlet>
    
            <servlet-name>springmvc</servlet-name>
            <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
            
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/config/springmvc-config.xml</param-value>
            </init-param>
            
            <load-on-startup>1</load-on-startup>
            
            <multipart-config>
                <max-file-size>20848820</max-file-size>
                <max-request-size>418018841</max-request-size>
                <file-size-threshold>1048576</file-size-threshold>
            </multipart-config>
            
        </servlet>
        
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        
    </web-app>

    Spring MVC配置文件,这里multipartResolver引用的是StandardServletMultipartResolver

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/springcontext.xsd
        ">
    
        <!-- 扫描目标包中的类 -->
        <context:component-scan base-package="com.xsl.controller" />
        <context:component-scan base-package="com.xsl.service" />
        
        <!-- 注册用于支持基于注解的控制器的请求处理方法的bean对象 -->
        <mvc:annotation-driven />
        
        <!-- 指示Spring MVC哪些静态资源需要单独处理,不需要dispatcher servlet -->
        <mvc:resources mapping="/css/**" location="/css/" />
        <mvc:resources mapping="/*.html" location="/" />
        <mvc:resources mapping="/image/**" location="/image/" />
    
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
        </bean>
        
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="basename" value="/WEB-INF/resource/messages" />
        </bean>
        
        <bean id="multipartResolver" class="org.springframework.web.support.StandardServletMultipartResolver">
        </bean>
    
    </beans>
  • 相关阅读:
    阅读笔记十四
    惨淡的蓝桥杯国赛经历
    阅读笔记十三
    阅读笔记十二
    阅读笔记十一
    阅读笔记十
    阅读笔记九
    阅读笔记八
    阅读笔记七
    阅读笔记六
  • 原文地址:https://www.cnblogs.com/xsl1995/p/10179081.html
Copyright © 2020-2023  润新知