利用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值