天天看點

使用springMVC實作檔案上傳和下載下傳之環境配置與上傳

最近的項目中用到了檔案的上傳和下載下傳功能,任務配置設定給了其他的同時完成。如今項目結束告一段落,我覺着這個功能比較重要,是以特意把它提取出來自己進行了嘗試。

一、 基礎配置:

maven導包及配置pom.xml,導包時除開springmvc的基礎依賴外,需要導入檔案上傳下載下傳時用到的commons-io.jsr和commons-fileupload.jar:

使用springMVC實作檔案上傳和下載下傳之環境配置與上傳

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"  

  xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  

  <modelversion>4.0.0</modelversion>  

  <groupid>filloadtest</groupid>  

  <artifactid>filloadtest</artifactid>  

  <packaging>war</packaging>  

  <version>0.0.1-snapshot</version>  

  <name>filloadtest maven webapp</name>  

  <url>http://maven.apache.org</url>  

   <build>  

    <finalname>filloadtest</finalname>  

     <plugins>    

            <!-- 以下配置可以保證每次強制更新時jre版本不會變化,那我的eclipse4.4.1,maven3.2.5為例,如果不設定這個,每次強制更新時jre就會變回1.5 -->    

            <plugin>    

                <artifactid>maven-compiler-plugin</artifactid>    

                <version>2.3.2</version>    

                <configuration>    

                    <source>1.7</source>    

                    <target>1.7</target>    

                    <encoding>utf-8</encoding>    

                    <compilerarguments>    

                        <verbose />    

                        <bootclasspath>${java.home}\lib\rt.jar</bootclasspath>    

                    </compilerarguments>    

                </configuration>    

            </plugin>    

        </plugins>    

  </build>  

  <dependencies>  

    <dependency>  

      <groupid>junit</groupid>  

      <artifactid>junit</artifactid>  

      <version>3.8.1</version>  

      <scope>test</scope>  

    </dependency>  

        <groupid>org.springframework</groupid>  

        <artifactid>spring-webmvc</artifactid>  

        <version>4.0.6.release</version>  

        <groupid>com.fasterxml.jackson.core</groupid>  

        <artifactid>jackson-annotations</artifactid>  

        <version>2.2.3</version>  

        <artifactid>jackson-core</artifactid>  

        <artifactid>jackson-databind</artifactid>  

        <groupid>commons-fileupload</groupid>  

        <artifactid>commons-fileupload</artifactid>  

        <version>1.3.1</version>  

        <groupid>commons-io</groupid>  

        <artifactid>commons-io</artifactid>  

        <version>2.4</version>  

  </dependencies>  

</project>  

web.xml基礎配置:

使用springMVC實作檔案上傳和下載下傳之環境配置與上傳

<?xml version="1.0" encoding="utf-8"?>  

<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"  

    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  

    xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  

    id="webapp_id" version="2.5">      

    <filter>  

        <description>字元集過濾器</description>  

        <filter-name>encodingfilter</filter-name>  

        <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>  

        <init-param>  

            <description>字元集編碼</description>  

            <param-name>encoding</param-name>  

            <param-value>utf-8</param-value>  

        </init-param>  

    </filter>  

    <filter-mapping>  

        <url-pattern>/*</url-pattern>  

    </filter-mapping>  

    <servlet>    

        <servlet-name>springmvc</servlet-name>    

        <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>    

        <init-param>    

            <param-name>contextconfiglocation</param-name>    

            <param-value>classpath:spring.xml</param-value>    

        </init-param>      

    </servlet>    

    <servlet-mapping>    

        <url-pattern>*.do</url-pattern>    

    </servlet-mapping>  

    <welcome-file-list>  

        <welcome-file>index.html</welcome-file>  

        <welcome-file>index.htm</welcome-file>  

        <welcome-file>index.jsp</welcome-file>  

        <welcome-file>default.html</welcome-file>  

        <welcome-file>default.htm</welcome-file>  

        <welcome-file>default.jsp</welcome-file>  

    </welcome-file-list>    

</web-app>    

spring基礎配置spring.xml:

使用springMVC實作檔案上傳和下載下傳之環境配置與上傳

<?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"    

    xmlns:mvc="http://www.springframework.org/schema/mvc"      

    xsi:schemalocation="    

        http://www.springframework.org/schema/beans     

        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    

        http://www.springframework.org/schema/context     

        http://www.springframework.org/schema/context/spring-context-3.0.xsd  

        http://www.springframework.org/schema/mvc   

        http://www.springframework.org/schema/mvc/spring-mvc.xsd">    

    <context:annotation-config />    

    <mvc:annotation-driven />  

    <context:component-scan base-package="controllers" />    

    <!-- 避免ie執行ajax時,傳回json出現下載下傳檔案 -->  

    <bean id="mappingjacksonhttpmessageconverter"  

        class="org.springframework.http.converter.json.mappingjackson2httpmessageconverter">  

        <property name="supportedmediatypes">  

            <list>  

                <value>text/html;charset=utf-8</value>  

            </list>  

        </property>  

    </bean>  

    <!-- 啟動spring mvc的注解功能,完成請求和注解pojo的映射 -->  

    <bean  

        class="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter">  

        <property name="messageconverters">  

                <ref bean="mappingjacksonhttpmessageconverter" /><!-- json轉換器 -->  

    <!-- 支援上傳檔案 -->  

    <bean id="multipartresolver"  

        class="org.springframework.web.multipart.commons.commonsmultipartresolver" >  

        <!-- 100m -->  

        <property name="maxuploadsize" value="104857600"></property>      

        <property name="defaultencoding" value="utf-8"></property>     

</beans>    

二、檔案上傳的代碼

上傳的簡單頁面index.html,要注意form表單送出時的entype的設定:

使用springMVC實作檔案上傳和下載下傳之環境配置與上傳

<!doctype html>  

<html>  

<head>  

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />  

</head>  

<body>  

   <form action="./uploadfile.do" method="post" enctype="multipart/form-data">  

                 選擇檔案:<input type="file" name="file"/>  

                 <input type="submit" value="送出"/>  

   </form>  

</body>  

</html>  

上傳對應的背景java代碼,具體問題見注釋:

使用springMVC實作檔案上傳和下載下傳之環境配置與上傳

package controllers;  

import java.io.file;  

import java.io.ioexception;  

import java.util.iterator;  

import javax.servlet.http.httpservletrequest;  

import org.apache.commons.io.fileutils;  

import org.springframework.http.httpheaders;  

import org.springframework.http.httpstatus;  

import org.springframework.http.mediatype;  

import org.springframework.http.responseentity;  

import org.springframework.stereotype.controller;  

import org.springframework.web.bind.annotation.requestmapping;  

import org.springframework.web.bind.annotation.requestmethod;  

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.commonsmultipartresolver;  

@controller  

public class filecontroller {  

    /** 

     * 檔案上傳 

     *  

     * @author:tuzongxun 

     * @title: uploadfile 

     * @param @param file 

     * @param @param request 

     * @param @throws illegalstateexception 

     * @param @throws ioexception 

     * @return void 

     * @date apr 28, 2016 1:22:00 pm 

     * @throws 

     */  

    @requestmapping(value = "/uploadfile.do", method = requestmethod.post)  

    public void uploadfile(httpservletrequest request)  

            throws illegalstateexception, ioexception {  

        // @requestparam("file") multipartfile file,  

        commonsmultipartresolver multipartresolver = new commonsmultipartresolver(  

                request.getsession().getservletcontext());  

        // 判斷 request 是否有檔案上傳,即多部分請求  

        if (multipartresolver.ismultipart(request)) {  

            // 轉換成多部分request  

            multiparthttpservletrequest multirequest = (multiparthttpservletrequest) request;  

            // 取得request中的所有檔案名  

            iterator<string> iter = multirequest.getfilenames();  

            while (iter.hasnext()) {  

                // 取得上傳檔案  

                multipartfile f = multirequest.getfile(iter.next());  

                if (f != null) {  

                    // 取得目前上傳檔案的檔案名稱  

                    string myfilename = f.getoriginalfilename();  

                    // 如果名稱不為“”,說明該檔案存在,否則說明該檔案不存在  

                    if (myfilename.trim() != "") {  

                        // 定義上傳路徑  

                        string path = "c:\\users\\tuzongxun123\\desktop\\"  

                                + myfilename;  

                        file localfile = new file(path);  

                        f.transferto(localfile);  

                    }  

                }  

            }  

        }  

    }  

}  

頁面效果圖如下,當選擇檔案送出後,便會看到選中的檔案被傳到了代碼中指定的位置,這裡是我的桌面上。

使用springMVC實作檔案上傳和下載下傳之環境配置與上傳