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

 

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

 

首先是web.xmlphp

[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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   
  3.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  4.     <servlet>  
  5.         <description>配置SpringMVC的前端控制器</description>  
  6.         <servlet-name>upload</servlet-name>  
  7.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  8.         <init-param>  
  9.             <param-name>contextConfigLocation</param-name>  
  10.             <param-value>classpath:applicationContext.xml</param-value>  
  11.         </init-param>  
  12.         <load-on-startup>1</load-on-startup>  
  13.     </servlet>  
  14.     <servlet-mapping>  
  15.         <servlet-name>upload</servlet-name>  
  16.         <url-pattern>/</url-pattern>  
  17.     </servlet-mapping>  
  18.       
  19.     <filter>  
  20.         <description>解決參數傳遞過程當中的亂碼問題</description>  
  21.         <filter-name>CharacterEncodingUTF8</filter-name>  
  22.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  23.         <init-param>  
  24.             <param-name>encoding</param-name>  
  25.             <param-value>UTF-8</param-value>  
  26.         </init-param>  
  27.     </filter>  
  28.     <filter-mapping>  
  29.         <filter-name>CharacterEncodingUTF8</filter-name>  
  30.         <url-pattern>/*</url-pattern>  
  31.     </filter-mapping>  
  32. </web-app>  

 

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

[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  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
[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <h1>文件過大,請從新選擇</h1>  

下面是用於選擇文件的上傳頁面index.jsp
[html]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <!-- 此處不能簡寫爲<script type="text/javascript" src=".."/> -->  
  3. <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>  
  4. <script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>  
  5.   
  6. <script type="text/javascript">  
  7. function ajaxFileUpload(){  
  8.     //開始上傳文件時顯示一個圖片,文件上傳完成將圖片隱藏  
  9.     //$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});  
  10.     //執行上傳文件操做的函數  
  11.     $.ajaxFileUpload({  
  12.         //處理文件上傳操做的服務器端地址(能夠傳參數,已親測可用)  
  13.         url:'${pageContext.request.contextPath}/test/fileUpload?uname=玄玉',  
  14.         secureuri:false,                           //是否啓用安全提交,默認爲false   
  15.         fileElementId:'myBlogImage',               //文件選擇框的id屬性  
  16.         dataType:'text',                           //服務器返回的格式,能夠是json或xml等  
  17.         success:function(data, status){            //服務器響應成功時的處理函數  
  18.             data = data.replace(/<pre.*?>/g, '');  //ajaxFileUpload會對服務器響應回來的text內容加上<pre style="....">text</pre>先後綴  
  19.             data = data.replace(/<PRE.*?>/g, '');  
  20.             data = data.replace("<PRE>", '');  
  21.             data = data.replace("</PRE>", '');  
  22.             data = data.replace("<pre>", '');  
  23.             data = data.replace("</pre>", '');     //本例中設定上傳文件完畢後,服務端會返回給前臺[0`filepath]  
  24.             if(data.substring(0, 1) == 0){         //0表示上傳成功(後跟上傳後的文件路徑),1表示失敗(後跟失敗描述)  
  25.                 $("img[id='uploadImage']").attr("src", data.substring(2));  
  26.                 $('#result').html("圖片上傳成功<br/>");  
  27.             }else{  
  28.                 $('#result').html('圖片上傳失敗,請重試!!');  
  29.             }  
  30.         },  
  31.         error:function(data, status, e){ //服務器響應失敗時的處理函數  
  32.             $('#result').html('圖片上傳失敗,請重試!!');  
  33.         }  
  34.     });  
  35. }  
  36. </script>  
  37.   
  38. <div id="result"></div>  
  39. <img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico">  
  40.   
  41. <input type="file" id="myBlogImage" name="myfiles"/>  
  42. <input type="button" value="上傳圖片" onclick="ajaxFileUpload()"/>  
  43.   
  44. <!--   
  45. AjaxFileUpload簡介  
  46. 官網:http://phpletter.com/Our-Projects/AjaxFileUpload/  
  47. 簡介:jQuery插件AjaxFileUpload可以實現無刷新上傳文件,而且簡單易用,它的使用人數不少,很是值得推薦  
  48. 注意:引入js的順序(它依賴於jQuery)和頁面中並沒有表單(只是在按鈕點擊的時候觸發ajaxFileUpload()方法)  
  49. 常見錯誤及解決方案以下  
  50. 1)SyntaxError: missing ; before statement  
  51.   --檢查URL路徑是否能夠訪問  
  52. 2)SyntaxError: syntax error  
  53.   --檢查處理提交操做的JSP文件是否存在語法錯誤  
  54. 3)SyntaxError: invalid property id  
  55.   --檢查屬性ID是否存在  
  56. 4)SyntaxError: missing } in XML expression  
  57.   --檢查文件域名稱是否一致或不存在  
  58. 5)其它自定義錯誤  
  59.   --可以使用變量$error直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示仍是方便不少  
  60.  -->  
最後是處理文件上傳的FileUploadController.java

 

[java]  view plain copy print ? 在CODE上查看代碼片 派生到個人代碼片
  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
相關文章
相關標籤/搜索