1. 程式人生 > >SpringMVC和jQuery的Ajax簡單檔案上傳下載示例

SpringMVC和jQuery的Ajax簡單檔案上傳下載示例

準備工作: 
前端引入:1、jquery,我在這裡用的是:jquery-1.10.2.min.js 
        2、ajaxfileupload.js 
這裡可能會報一些錯,所以在json判斷那裡修改為(網上也有): 
Js程式碼  收藏程式碼
  1. if ( type == "json" ){  
  2.    data = r.responseText;     
  3.    var start = data.indexOf(">");     
  4.    if(start != -1) {     
  5.       var end = data.indexOf("<", start + 1);     
  6.       if(end != -1) {     
  7.          data = data.substring(start + 1, end);     
  8.       }     
  9.    }   
  10.    eval( "data = " + data );  
  11. }  

末尾那裡補充一段: 
Js程式碼  收藏程式碼
  1. handleError: function( s, xhr, status, e ) {  
  2.   if ( s.error ) {  
  3.        s.error.call( s.context || window, xhr, status, e );  
  4.   }  
  5.   if ( s.global ) {  
  6.      (s.context ? jQuery(s.context) : jQuery.event).trigger  ( "ajaxError", [xhr, s, e] );  
  7.   }  
  8. }  

後臺匯入spring的jar包,我這裡用的是:spring3.0.5 
在spring.xml裡配置如下: 
Xml程式碼  收藏程式碼
  1. <!-- SpringMVC上傳檔案時,需要配置MultipartResolver處理器 -->    
  2.    <bean id="multipartResolver"
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
  3.        <property name="defaultEncoding" value="UTF-8"/>    
  4.        <!-- 指定所上傳檔案的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個檔案,而是所有檔案的容量之和 -->    
  5.        <!-- 不在這裡限制了,後臺各自進行限制了  
  6.        <property name="maxUploadSize" value="2000000"/>   
  7.        -->   
  8.     </bean>   
  9.     <!-- SpringMVC在超出上傳檔案限制時,會丟擲org.springframework.web.multipart.MaxUploadSizeExceededException -->    
  10.    <!-- 該異常是SpringMVC在檢查上傳的檔案資訊時丟擲來的,而且此時還沒有進入到Controller方法中 -->    
  11.    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">    
  12.        <property name="exceptionMappings">    
  13.            <props>    
  14.                <!-- 遇到MaxUploadSizeExceededException異常時,跳轉到/page/html/errorGolbal.html頁面 -->    
  15.                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/page/html/errorGolbal.html</prop>    
  16.            </props>    
  17.        </property>    
  18.    </bean>  

這裡就充分利用框架的便利性幫你都做好了,如果你不在xml裡配置這些,那麼在controller那裡,request.getInputStream()得到的這個流不全是檔案流,還包含了其他,需要你自己編碼去解析,當然,要解析的話還要知道http相關報文解析知識,所以這裡可以充分利用框架的便利性,有興趣的可以研究下

好了,準備工作做好了,看下前端的具體程式碼: 
Html程式碼  收藏程式碼
  1. <div id="fileUpLoad" class="manage">  
  2.     添附檔案  
  3.     <!-- 自定義 <input type="file"/> -->  
  4.     <input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden" />  
  5.     <input type="text" id="txtFoo" readonly="readonly" style="width: 300px" />           
  6.     <button onclick="btnFile.click()" style="height: 25px;">選擇檔案</button>  
  7. </div>  

js程式碼為: 
Js程式碼  收藏程式碼
  1. if (!window.com) {  
  2.     window.com = {};  
  3. }  
  4. if (!window.com.company) {  
  5.     window.com.company= {};  
  6. }  
  7. if (!window.com.company.project) {  
  8.     window.com.company.project= {};  
  9. }  
  10. if (!window.com.company.project.services) {  
  11.     window.com.company.project.services = {};  
  12. }  
  13. if (!window.com.company.project.services.newCase) {  
  14.     window.com.company.project.services.newCase = {};  
  15. }  
  16. //生成隨機guid數(參考網上)  
  17. com.company.project.services.newCase.getGuidGenerator = function() {   
  18.     var S4 = function() {   
  19.        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);   
  20.     };   
  21.     return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());   
  22. };  
  23. //上傳檔案  
  24. com.company.project.services.newCase.fileUpLoad = function(){  
  25.     var fileName = $("#btnFile").val();//檔名  
  26.     fileName = fileName.split("\\");  
  27.     fileName = fileName[fileName.length-1];  
  28.     var guid = com.company.project.services.newCase.getGuidGenerator();//唯一標識guid  
  29.     var data = {guid:guid};  
  30.     jQuery.ajaxSettings.traditional = true;  
  31.     $.ajaxFileUpload({  
  32.         url : '/PROJECT/function.do?method=fileUpLoad',  
  33.         secureuri : false,//安全協議  
  34.         fileElementId:'btnFile',//id  
  35.         type : 'POST',  
  36.         dataType : 'json',  
  37.         data:data,  
  38.         async : false,  
  39.         error : function(data,status,e) {  
  40.             alert('Operate Failed!');  
  41.         },  
  42.         success : function(json) {  
  43.             if (json.resultFlag==false){  
  44.                 alert(json.resultMessage);  
  45.             }else{  
  46.                 alert('檔案上傳成功!');  
  47.                 var next = $("#fileUpLoad").html();  
  48.                 $("#fileUpLoad").html("<div id='"+guid+"'>"+"檔案:"+fileName+"   <a href='#' onclick='com.company.project.services.newCase.filedelete("+"\""+guid+"\""+","+"\""+fileName+"\""+")'>刪除</a>"+"<br/></div>");  
  49.                 $("#fileUpLoad").append(next);  
  50.             }  
  51.         }  
  52.     });  
  53. };  
  54. //檔案刪除  
  55. com.company.project.services.newCase.filedelete = function(guid,fileName){  
  56.     jQuery.ajaxSettings.traditional = true;  
  57.     var data = {guid:guid,fileName:fileName};  
  58.     $.ajax({  
  59.         url : '/PROJECT/function.do?method=filedelete',  
  60.         type : 'POST',  
  61.         dataType : 'json',  
  62.         data:data,  
  63.         async : false,  
  64.         error : function() {  
  65.             alert('Operate Failed!');  
  66.         },  
  67.         success : function(json) {  
  68.             if (json.resultFlag==false){  
  69.                 alert(json.resultMessage);  
  70.             }else{  
  71.                 alert('刪除成功!');  
  72.                 $("#"+guid).remove();  
  73.             }  
  74.         }  
  75.     });  
  76. };  


---------------------------------------------------------------------------------- 

注:如果你對ajax不熟悉,或者由於瀏覽器等原因,致使上述方式提交出現各種問題,那麼你可以用form表單形式提交,程式碼片段如下:
Html程式碼  收藏程式碼
  1. <div id="fileUpLoad" class="manage">  
  2.     <form id="needHide" action="/工程/function.do?method=fileUpLoad" method="post" enctype="multipart/form-data" target = "hidden_frame">  
  3.     <!-- 自定義 <input type="file"/> -->  
  4.     <input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden"/>  
  5.     </form>  
  6.     添附檔案  
  7.     <input type="text" id="txtFoo" readonly="readonly" style="width: 300px" />           
  8.     <button onclick="btnFile.click()" style="height: 25px;">選擇檔案</button>  
  9.