利用Jquery使用HTML5的FormData屬性實現對文件的上傳


1.利用Jquery使用HTML5的FormData屬性實現對文件的上傳

  在HTML5以前我們如果需要實現文件上傳服務器等功能的時候,有時候我們不得不依賴於FLASH去實現,而在HTML5到來之后,我們很容易的實現對文件的上傳,只需要利用HTML5的一個FormData屬性,結合Jquery就很容易實現文件的上傳,而且讀取文件的上傳進度,下面這個上傳案例就是基於上面所說的實現的,下面我將所所有的JS和CSS以及HTML頁面代碼放在下面。

  注意事項:FormData屬性必須依賴於HTML5,所以如果你按照本文代碼實現的功能,則瀏覽器必須升級為最新(支持HTML5 FormData屬性)。

2.HTML頁面代碼如下

 1 <!DOCTYPE html>
 2 
 3 <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
 4     <head>
 5         <meta charset="utf-8" />
 6         <title>使用HTML的FormData屬性實現文件上傳</title>
 7         <link rel="stylesheet" href="../css/fileUpload.css" />
 8     </head>
 9     <body>
10         <table id="uploadTable" style="border: 1px;"></table>
11         <br/>
12         <a href="javascript:void(0);" class="input-file">
13             添加文件<input type="file" id="txtFile" style="width:200px;" />
14         </a>
15         <script type="text/javascript" src="../js/jquery-1.7.1-min.js"></script>
16 
17         <script type="text/javascript">
18             $(function () {
19                 $('#uploadTable').SalesMOUNDUpload({
20                     saveUrl: '/Test/Save',
21                     jqInput: $('#txtFile'),
22                     fnRemove: removeFile,
23                     fnComplete: function (d) {
24                         window.console.log('complete ' + d);
25                     }
26                 });
27             });
28             function removeFile(d) {
29                 $.post('/Test/Remove', { "filename": d }, function(r) {
30                     
31                 });
32             }
33         </script>
34     </body>
35 </html>

3.CSS代碼如下:

 1  /*源文件頭信息:
 2  <copyright file="FileUpload.js">
 3  Copyright(c)2014-2034 Kencery.All rights reserved.
 4  個人博客:http://www.cnblogs.com/hanyinglong
 5  創建人:韓迎龍(kencery)
 6  創建時間:2015-6-24
 7  </copyright>*/
 8 
 9 body
10 {
11     font-family: "微軟雅黑";
12     font-size: 12px;
13 }
14 .input-file {
15     overflow: hidden;
16     position: relative;
17 }
18 .input-file input {
19     opacity: 0;
20     filter: alpha(opacity=0);
21     font-size: 100px;
22     position: absolute;
23     top: 0;
24     right: 0;
25 }
26 #uploadTable {
27     width: 500px;
28     border-collapse: collapse;
29     border: 1px solid Silver;
30 }

4.JS代碼如下:

  1 // 源文件頭信息:
  2 // <copyright file="FileUpload.js">
  3 // Copyright(c)2014-2034 Kencery.All rights reserved.
  4 // 個人博客:http://www.cnblogs.com/hanyinglong
  5 // 創建人:韓迎龍(kencery)
  6 // 創建時間:2015-6-24
  7 // </copyright>
  8 
  9 ;
 10 (function($) {
 11     $.fn.SalesMOUNDUpload = function(options) {
 12         var defaults =
 13         {
 14             saveUrl: '',
 15             jqInput: '',
 16             maxSize: 1024 * 1024 * 100, //100M
 17             fnRemove: '', //移除文件 ,參數:文件名
 18             fnComplete: '' //每個文件成功 ,參數:服務器端返回內容
 19         };
 20 
 21         var opt = $.extend(defaults, options);
 22 
 23         function getByteToM(val) {
 24             if (isNaN(val)) return val;
 25             val = val / (1024 * 1024);
 26             val = Math.round(val * 100) / 100;
 27             return val;
 28         }
 29 
 30         return this.each(function() {
 31             var $this = $(this);
 32             $this.empty();
 33 
 34             if (typeof FormData == 'undefine') {
 35                 alert('瀏覽器版本太低,不支持改上傳!');
 36                 return;
 37             }
 38 
 39             //表頭
 40             if ($this.find('thead').length == 0) {
 41                 var $thead = $('<thead>');
 42                 var $th_tr = $('<tr>');
 43                 $th_tr.append('<th>文件名</th>');
 44                 $th_tr.append('<th>類型</th>');
 45                 $th_tr.append('<th>大小</th>');
 46                 $th_tr.append('<th>狀態</th>');
 47                 $th_tr.append('<th>操作</th>');
 48                 $th_tr.appendTo($thead);
 49                 $this.append($thead);
 50             }
 51 
 52             opt.jqInput[0].addEventListener('change', function(e) {
 53                 var file = this.files[0];
 54 
 55                 if (!file) {
 56                     return;
 57                 }
 58                 if (file.size > opt.maxSize) {
 59                     window.alert('文件超過最大');
 60                     return;
 61                 }
 62                 var fd = new FormData();
 63                 var $table = $this;
 64 
 65                 fd.append("uploadFile", file);
 66                 var xhr = new XMLHttpRequest();
 67                 xhr.open('POST', opt.saveUrl, true);
 68 
 69                 xhr.upload.addEventListener("progress", uploadProgress, false);
 70                 xhr.addEventListener("load", uploadComplete, false);
 71                 xhr.addEventListener("error", uploadFailed, false);
 72                 xhr.addEventListener("abort", uploadCanceled, false);
 73 
 74                 //表中內容
 75                 var $tr = $('<tr>');
 76                 $tr.append('<td class="upload_name">' + file.name + '</td>');
 77                 $tr.append('<td class="upload_type">' + file.type + '</td>');
 78                 $tr.append('<td class="upload_size">' + getByteToM(file.size) + 'M' + '</td>');
 79                 $tr.append('<td class="upload_status">' + 0 + '</td>');
 80                 $tr.append('<td class="upload_action"><a href="javascript:void(0);">' + '取消' + '</a></td>');
 81                 $tr.find('.upload_action a').unbind('click').bind('click', function() {
 82                     xhr.abort();
 83                 });
 84 
 85                 $table.append($tr);
 86 
 87                 function uploadProgress(evt) {
 88                     if (evt.lengthComputable) {
 89                         var percentComplete = Math.round(evt.loaded * 100 / evt.total);
 90                         $tr.find('.upload_status').html(Math.round(percentComplete) + '%');
 91                     } else {
 92                         $tr.find('.upload_status').html('unable to compute');
 93                     }
 94                 }
 95 
 96                 function uploadComplete(evt) {
 97                     if (evt.target.status == 200) {
 98                         $tr.find('.upload_status').html('已完成');
 99                         $tr.find('.upload_action a').html('刪除');
100                         if (typeof opt.fnComplete == 'function') {
101                             opt.fnComplete(evt.target.response);
102 
103                         }
104                         $tr.find('.upload_action').unbind('click').bind('click', removeFile);
105                     }
106                 }
107 
108                 function uploadFailed() {
109                     $tr.find('.upload_status').html('<a href="javascript:void(0);">×</a>');
110                     $tr.find('.upload_status a').unbind('click').bind('click', function() {
111                         $tr.remove();
112                     });
113                     $tr.find('.upload_action a').html('重試');
114                     $tr.find('.upload_action a').unbind('click').bind('click', function() {
115                         xhr.send(fd);
116                     });
117                 }
118 
119                 function uploadCanceled() {
120                     $tr.remove();
121                 }
122 
123                 function removeFile() {
124                     $tr.remove();
125                     if (typeof opt.fnRemove == 'function') {
126                         opt.fnRemove(file.name);
127                     }
128                 }
129 
130                 xhr.send(fd);
131             }, false);
132         });
133     };
134 }(jQuery));

5.代碼查看地址:https://github.com/kencery/Common/tree/master/KenceryCommonMethod/%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0


免責聲明!

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



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