Jquery異步上傳文件


我想通過jQuery異步上傳文件,這是我的HTML:

 

1
2
3
<span>File</span>
<input type= "file"  id= "file"  name= "file"  size= "10" />
<input id= "uploadbutton"  type= "button"  value= "Upload" />

這是我的javascript:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function () {
   $( "#uploadbutton" ).click(function () {
     var filename = $( "#file" ).val();
 
     $.ajax({
       type:  "POST" ,
       url:  "addFile.do" ,
       enctype:  'multipart/form-data' ,
       data: {
         file: filename
       },
       success: function () {
         alert( "Data Uploaded: " );
       }
     });
   });
});

我只得到上傳的文件名,咋辦?

 

我現在用了 jQuery Form插件來解決這個問題:http://malsup.com/jquery/form/#code-samples

有沒有不用該插件來實現呢?

 

解決方法:

可以采用HTML5,用jQuery,Ajax實現文件上傳,不僅如此,你可以做文件驗證(名稱,大小,MIME類型)或利用HTML5的進度標簽(或者div)處理進度事件。

 

最近我也在做文件上傳,我不想用flash、iframe或其它插件,經過一番研究,我想出了解決方案。

HTML:

 

1
2
3
4
5
<form enctype= "multipart/form-data" >
<input name= "file"  type= "file"  />
<input type= "button"  value= "Upload"  />
</form>
<progress></progress>

首先,你可以做一些驗證,例如文件的onChange事件:

 

1
2
3
4
5
6
7
$( ':file' ).change(function(){
     var file =  this .files[0];
     name = file.name;
     size = file.size;
     type = file.type;
     //your validation
});

按鈕點擊觸發Ajax:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$( ':button' ).click(function(){
     var formData =  new  FormData($( 'form' )[0]);
     $.ajax({
         url:  'upload.php' ,   //server script to process data
         type:  'POST' ,
         xhr: function() {   // custom xhr
             myXhr = $.ajaxSettings.xhr();
             if (myXhr.upload){  // check if upload property exists
                 myXhr.upload.addEventListener( 'progress' ,progressHandlingFunction,  false );  // for handling the progress of the upload
             }
             return  myXhr;
         },
         //Ajax事件
         beforeSend: beforeSendHandler,
         success: completeHandler,
         error: errorHandler,
         // Form數據
         data: formData,
         //Options to tell JQuery not to process data or worry about content-type
         cache:  false ,
         contentType:  false ,
         processData:  false
     });
});

處理進度:

 

1
2
3
4
5
function progressHandlingFunction(e){
     if (e.lengthComputable){
         $( 'progress' ).attr({value:e.loaded,max:e.total});
     }
}

 

 

HTML5的文件上傳非常簡單,但必須在支持HTML5的瀏覽器中運行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM