1. 程式人生 > >SpringMVC結合ajaxfileupload.js實現文件無刷新上傳

SpringMVC結合ajaxfileupload.js實現文件無刷新上傳

[0 enc name 完整 可用 ctype per 文件路徑 .html

完整版見https://jadyer.github.io/2012/05/17/springmvc-annotation/

直接看代碼吧,註釋都在裏面

首先是web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5" 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_2_5.xsd"
> <servlet> <description>配置SpringMVC的前端控制器</description> <servlet-name>upload</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name
>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>upload</
servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <description>解決參數傳遞過程中的亂碼問題</description> <filter-name>CharacterEncodingUTF8</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingUTF8</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

下面是位於//src//applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2 <beans xmlns="http://www.springframework.org/schema/beans"  
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 4     xmlns:mvc="http://www.springframework.org/schema/mvc"  
 5     xmlns:context="http://www.springframework.org/schema/context"  
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans   
 7                         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
 8                         http://www.springframework.org/schema/mvc  
 9                         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
10                         http://www.springframework.org/schema/context   
11                         http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
12     <!-- 啟動Spring的組件自動掃描機制(Spring會自動掃描base-package指定的包中的類和子包裏面類) -->  
13     <!-- 此處可參考我的文章http://blog.csdn.net/jadyer/article/details/6038604 -->  
14     <context:component-scan base-package="com.jadyer"/>  
15       
16     <!-- 啟動SpringMVC的註解功能,它會自動註冊HandlerMapping、HandlerAdapter、ExceptionResolver的相關實例 -->  
17     <mvc:annotation-driven/>  
18       
19     <!-- 由於web.xml中設置SpringMVC攔截所有請求,所以在讀取靜態資源文件時就會讀不到 -->  
20     <!-- 通過此配置即可指定所有請求或引用"/js/**"的資源,都會從"/js/"中查找 -->  
21     <mvc:resources mapping="/js/**" location="/js/"/>  
22     <mvc:resources mapping="/upload/**" location="/upload/"/>  
23       
24     <!-- SpringMVC上傳文件時,需配置MultipartResolver處理器 -->  
25     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
26         <!-- 指定所上傳文件的總大小不能超過800KB......註意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 -->  
27         <property name="maxUploadSize" value="800000"/>  
28     </bean>  
29       
30     <!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
31     <!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,而且此時還沒有進入到Controller方法中 -->  
32     <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
33         <property name="exceptionMappings">  
34             <props>  
35                 <!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/jsp/error_fileupload.jsp頁面 -->  
36                 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>  
37             </props>  
38         </property>  
39     </bean>  
40       
41     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
42         <property name="prefix" value="/WEB-INF/jsp/"/>  
43         <property name="suffix" value=".jsp"/>  
44     </bean>  
45 </beans>  

下面是上傳文件內容過大時的提示頁面//WEB-INF//jsp//error_fileupload.jsp

1 <%@ page language="java" pageEncoding="UTF-8"%>  
2 <h1>文件過大,請重新選擇</h1> 

下面是用於選擇文件的上傳頁面index.jsp

<%@ page language="java" pageEncoding="UTF-8"%>  
<!-- 此處不能簡寫為<script type="text/javascript" src=".."/> -->  
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>  
<script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>  
  
<script type="text/javascript">  
function ajaxFileUpload(){  
    //開始上傳文件時顯示一個圖片,文件上傳完成將圖片隱藏  
    //$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});  
    //執行上傳文件操作的函數  
    $.ajaxFileUpload({  
        //處理文件上傳操作的服務器端地址(可以傳參數,已親測可用)  
        url:${pageContext.request.contextPath}/test/fileUpload?uname=玄玉,  
        secureuri:false,                           //是否啟用安全提交,默認為false   
        fileElementId:myBlogImage,               //文件選擇框的id屬性  
        dataType:text,                           //服務器返回的格式,可以是json或xml等  
        success:function(data, status){            //服務器響應成功時的處理函數  
            data = data.replace(/<pre.*?>/g, ‘‘);  //ajaxFileUpload會對服務器響應回來的text內容加上<pre style="....">text</pre>前後綴  
            data = data.replace(/<PRE.*?>/g, ‘‘);  
            data = data.replace("<PRE>", ‘‘);  
            data = data.replace("</PRE>", ‘‘);  
            data = data.replace("<pre>", ‘‘);  
            data = data.replace("</pre>", ‘‘);     //本例中設定上傳文件完畢後,服務端會返回給前臺[0`filepath]  
            if(data.substring(0, 1) == 0){         //0表示上傳成功(後跟上傳後的文件路徑),1表示失敗(後跟失敗描述)  
                $("img[id=‘uploadImage‘]").attr("src", data.substring(2));  
                $(#result).html("圖片上傳成功<br/>");  
            }else{  
                $(#result).html(圖片上傳失敗,請重試!!);  
            }  
        },  
        error:function(data, status, e){ //服務器響應失敗時的處理函數  
            $(#result).html(圖片上傳失敗,請重試!!);  
        }  
    });  
}  
</script>  
  
<div id="result"></div>  
<img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico">  
  
<input type="file" id="myBlogImage" name="myfiles"/>  
<input type="button" value="上傳圖片" onclick="ajaxFileUpload()"/>  
  
<!--   
AjaxFileUpload簡介  
官網:http://phpletter.com/Our-Projects/AjaxFileUpload/  
簡介:jQuery插件AjaxFileUpload能夠實現無刷新上傳文件,並且簡單易用,它的使用人數很多,非常值得推薦  
註意:引入js的順序(它依賴於jQuery)和頁面中並無表單(只是在按鈕點擊的時候觸發ajaxFileUpload()方法)  
常見錯誤及解決方案如下  
1)SyntaxError: missing ; before statement  
  --檢查URL路徑是否可以訪問  
2)SyntaxError: syntax error  
  --檢查處理提交操作的JSP文件是否存在語法錯誤  
3)SyntaxError: invalid property id  
  --檢查屬性ID是否存在  
4)SyntaxError: missing } in XML expression  
  --檢查文件域名稱是否一致或不存在  
5)其它自定義錯誤  
  --可使用變量$error直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多  
 -->  

最後是處理文件上傳的FileUploadController.java

  1 package com.jadyer.controller;  
  2   
  3 import java.io.File;  
  4 import java.io.IOException;  
  5 import java.io.PrintWriter;  
  6   
  7 import javax.servlet.http.HttpServletRequest;  
  8 import javax.servlet.http.HttpServletResponse;  
  9   
 10 import org.apache.commons.io.FileUtils;  
 11 import org.springframework.stereotype.Controller;  
 12 import org.springframework.web.bind.annotation.RequestMapping;  
 13 import org.springframework.web.bind.annotation.RequestParam;  
 14 import org.springframework.web.multipart.MultipartFile;  
 15   
 16 /** 
 17  * SpringMVC中的文件上傳 
 18  * 1)由於SpringMVC使用的是commons-fileupload實現,所以先要將其組件引入項目中 
 19  * 2)在SpringMVC配置文件中配置MultipartResolver處理器(可在此加入對上傳文件的屬性限制) 
 20  * 3)在Controller的方法中添加MultipartFile參數(該參數用於接收表單中file組件的內容) 
 21  * 4)編寫前臺表單(註意enctype="multipart/form-data"以及<input type="file" name="****"/>) 
 22  * PS:由於這裏使用了ajaxfileupload.js實現無刷新上傳,故本例中未使用表單 
 23  * --------------------------------------------------------------------------------------------- 
 24  * 這裏用到了如下的jar 
 25  * commons-io-2.4.jar 
 26  * commons-fileupload-1.3.jar 
 27  * commons-logging-1.1.2.jar 
 28  * spring-aop-3.2.4.RELEASE.jar 
 29  * spring-beans-3.2.4.RELEASE.jar 
 30  * spring-context-3.2.4.RELEASE.jar 
 31  * spring-core-3.2.4.RELEASE.jar 
 32  * spring-expression-3.2.4.RELEASE.jar 
 33  * spring-jdbc-3.2.4.RELEASE.jar 
 34  * spring-oxm-3.2.4.RELEASE.jar 
 35  * spring-tx-3.2.4.RELEASE.jar 
 36  * spring-web-3.2.4.RELEASE.jar 
 37  * spring-webmvc-3.2.4.RELEASE.jar 
 38  * --------------------------------------------------------------------------------------------- 
 39  * @create Sep 14, 2013 5:06:09 PM 
 40  * @author 玄玉<http://blog.csdn.net/jadyer> 
 41  */  
 42 @Controller  
 43 @RequestMapping("/test")  
 44 public class FileUploadController {  
 45     /** 
 46      * 這裏這裏用的是MultipartFile[] myfiles參數,所以前臺就要用<input type="file" name="myfiles"/> 
 47      * 上傳文件完畢後返回給前臺[0`filepath],0表示上傳成功(後跟上傳後的文件路徑),1表示失敗(後跟失敗描述) 
 48      */  
 49     @RequestMapping(value="/fileUpload")  
 50     public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{  
 51         //可以在上傳文件的同時接收其它參數  
 52         System.out.println("收到用戶[" + uname + "]的文件上傳請求");  
 53         //如果用的是Tomcat服務器,則文件會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夾中  
 54         //這裏實現文件上傳操作用的是commons.io.FileUtils類,它會自動判斷/upload是否存在,不存在會自動創建  
 55         String realPath = request.getSession().getServletContext().getRealPath("/upload");  
 56         //設置響應給前臺內容的數據格式  
 57         response.setContentType("text/plain; charset=UTF-8");  
 58         //設置響應給前臺內容的PrintWriter對象  
 59         PrintWriter out = response.getWriter();  
 60         //上傳文件的原名(即上傳前的文件名字)  
 61         String originalFilename = null;  
 62         //如果只是上傳一個文件,則只需要MultipartFile類型接收文件即可,而且無需顯式指定@RequestParam註解  
 63         //如果想上傳多個文件,那麽這裏就要用MultipartFile[]類型來接收文件,並且要指定@RequestParam註解  
 64         //上傳多個文件時,前臺表單中的所有<input type="file"/>的name都應該是myfiles,否則參數裏的myfiles無法獲取到所有上傳的文件  
 65         for(MultipartFile myfile : myfiles){  
 66             if(myfile.isEmpty()){  
 67                 out.print("1`請選擇文件後上傳");  
 68                 out.flush();  
 69                 return null;  
 70             }else{  
 71                 originalFilename = myfile.getOriginalFilename();  
 72                 System.out.println("文件原名: " + originalFilename);  
 73                 System.out.println("文件名稱: " + myfile.getName());  
 74                 System.out.println("文件長度: " + myfile.getSize());  
 75                 System.out.println("文件類型: " + myfile.getContentType());  
 76                 System.out.println("========================================");  
 77                 try {  
 78                     //這裏不必處理IO流關閉的問題,因為FileUtils.copyInputStreamToFile()方法內部會自動把用到的IO流關掉  
 79                     //此處也可以使用Spring提供的MultipartFile.transferTo(File dest)方法實現文件的上傳  
 80                     FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));  
 81                 } catch (IOException e) {  
 82                     System.out.println("文件[" + originalFilename + "]上傳失敗,堆棧軌跡如下");  
 83                     e.printStackTrace();  
 84                     out.print("1`文件上傳失敗,請重試!!");  
 85                     out.flush();  
 86                     return null;  
 87                 }  
 88             }  
 89         }  
 90         //此時在Windows下輸出的是[D:\Develop\apache-tomcat-6.0.36\webapps\AjaxFileUpload\\upload\憤怒的小鳥.jpg]  
 91         //System.out.println(realPath + "\\" + originalFilename);  
 92         //此時在Windows下輸出的是[/AjaxFileUpload/upload/憤怒的小鳥.jpg]  
 93         //System.out.println(request.getContextPath() + "/upload/" + originalFilename);  
 94         //不推薦返回[realPath + "\\" + originalFilename]的值  
 95         //因為在Windows下<img src="file:///D:/aa.jpg">能被firefox顯示,而<img src="D:/aa.jpg">firefox是不認的  
 96         out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);  
 97         out.flush();  
 98         return null;  
 99     }  
100 }  

註:本文參考:http://blog.csdn.net/jadyer/article/details/11693705

SpringMVC結合ajaxfileupload.js實現文件無刷新上傳