基于ajaxFileUpload,兼容ie7以上、chrome等浏览器的文件上传功能

来源:互联网 发布:php list注意 编辑:程序博客网 时间:2024/06/05 14:54

第一步:html中引入jQuery-1.7.1.js和ajaxFileUpload.js

复制代码
 1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4     <title>企业年金数据校验平台</title> 5     <link href="css/index.css" rel="stylesheet" type="text/css" /> 6 </head> 7 <body> 8     <div class="container"> 9         <div class="head">10             <div class="user-nav">11                 <div class="user-info">12                     <span id="username"></span><span class="logout can-click">退出</span>13                 </div>14             </div>15             <div class="nav-title">16                 <span>企业年金数据校验平台</span>17             </div>18 <!--            <div class="nav-attention">19                 <img alt="light" src="images/atten_light.gif" class="atten-light" />20                 <span class="">重要提醒:</span> <span>XXXXXXXXXXX</span>21             </div>-->22         </div>23         <div class="main">24             <div class="main-nav">25                 26             </div>27             <div class="main-top">28                 <div class="main-tl">29                     <div class="exl-submit">30                         <span class="exl-submit-til">Excel上传</span> <a class="btn-upload exl-submit-can"31                             id="btn-upload" href="#">32                             <input type="file" id="excel_upload" name="file" />33                         </a>34                     </div>35                 </div>36                 <div class="main-tr">37                 </div>38             </div>39             <div class="main-mid">40             </div>41             <div class="main-bottom">42                 <div id="loading_info" class="loading-info">43                 </div>44                 <div id="execute_result" class="execute-result">45                     <div id="result-step-two" class="result-wrap">46                         <div class="result-left"></div>47                         <div class="result-right"></div>48                     </div>49                     <div id="result-step-three" class="result-wrap">50                     </div>51                     <div id="result-step-four" class="result-wrap">52                     </div>53                     54                 </div>55             </div>56         </div>57     </div>58 </body>59 <script src="http://xxx.xxx.xxx.xxx/commonScript/jquery/jquery-1.7.1.min.js" type="text/javascript"></script>60 <script src="http://xxx.xxx.xxx.xxx/commonScript/format.js" type="text/javascript"></script>61 <script src="js/ajaxfileupload.js" type="text/javascript"></script>62 <script src="js/tools.js" type="text/javascript"></script>63 <script src="js/index.js" type="text/javascript"></script>64 </html>
复制代码

第二步:ajaxFileUpload.js代码

复制代码
  1 jQuery.extend({  2     handleError: function (s, xhr, status, e) {  3         // If a local callback was specified, fire it    4         if (s.error) {  5             s.error.call(s.context || s, xhr, status, e);  6         }  7   8         // Fire the global callback    9         if (s.global) { 10             (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]); 11         } 12     }, 13     createUploadIframe: function (id, uri) { 14  15         var frameId = 'jUploadFrame' + id; 16  17         if (window.ActiveXObject) { 18             if (jQuery.browser.version == "9.0") { 19                 io = document.createElement('iframe'); 20                 io.id = frameId; 21                 io.name = frameId; 22             } 23             else if (jQuery.browser.version == "6.0" || jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0") { 24  25                 var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); 26                 if (typeof uri == 'boolean') { 27                     io.src = 'javascript:false'; 28                 } 29                 else if (typeof uri == 'string') { 30                     io.src = uri; 31                 } 32             } 33         } 34         else { 35             var io = document.createElement('iframe'); 36             io.id = frameId; 37             io.name = frameId; 38         } 39         io.style.position = 'absolute'; 40         io.style.top = '-1000px'; 41         io.style.left = '-1000px'; 42  43         document.body.appendChild(io); 44  45         return io; 46     }, 47     ajaxUpload: function (s, xml) { 48         //if((fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0].name)))   49  50         var uid = new Date().getTime(), idIO = 'jUploadFrame' + uid, _this = this; 51         var jIO = $('<iframe name="' + idIO + '" id="' + idIO + '" style="display:none">').appendTo('body'); 52         var jForm = $('<form action="' + s.url + '" target="' + idIO + '" method="post" enctype="multipart/form-data" style="display:none"></form>').appendTo('body'); 53         var oldElement = $('#' + s.fileElementId); 54         var newElement = $(oldElement).clone(); 55         $(oldElement).attr('id', 'jUploadFile' + uid); 56         $(oldElement).before(newElement); 57         $(oldElement).appendTo(jForm); 58  59         this.remove = function () { 60             if (_this !== null) { 61                 jNewFile.before(jOldFile).remove(); 62                 jIO.remove(); jForm.remove(); 63                 _this = null; 64             } 65         } 66         this.onLoad = function () { 67  68             var data = $(jIO[0].contentWindow.document.body).text(); 69  70             try { 71  72                 if (data != undefined) { 73                     data = eval('(' + data + ')'); 74                     try { 75  76                         if (s.success) 77                             s.success(data, status); 78  79                         // Fire the global callback   80                         if (s.global) 81                             jQuery.event.trigger("ajaxSuccess", [xml, s]); 82                         if (s.complete) 83                             s.complete(data, status); 84                         xml = null; 85                     } catch (e) { 86  87                         status = "error"; 88                         jQuery.handleError(s, xml, status, e); 89                     } 90  91                     // The request was completed   92                     if (s.global) 93                         jQuery.event.trigger("ajaxComplete", [xml, s]); 94                     // Handle the global AJAX counter   95                     if (s.global && ! --jQuery.active) 96                         jQuery.event.trigger("ajaxStop"); 97  98                     // Process result   99 100                 }101             } catch (ex) {102                 alert(ex.message);103             };104         }105         this.start = function () { jForm.submit(); jIO.load(_this.onLoad); };106         return this;107 108     },109     createUploadForm: function (id, url, fileElementId, data) {110         //create form     111         var formId = 'jUploadForm' + id;112         var fileId = 'jUploadFile' + id;113         var form = jQuery('<form  action="' + url + '" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');114         if (data) {115             for (var i in data) {116                 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);117             }118         }119 120         var oldElement = jQuery('#' + fileElementId);121         var newElement = jQuery(oldElement).clone();122         jQuery(oldElement).attr('id', fileId);123         jQuery(oldElement).before(newElement);124         jQuery(oldElement).appendTo(form);125 126         //set attributes  127         jQuery(form).css('position', 'absolute');128         jQuery(form).css('top', '-1200px');129         jQuery(form).css('left', '-1200px');130         jQuery(form).appendTo('body');131         return form;132     },133     ajaxFileUpload: function (s) {134         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout      135         // Create the request object  136         var xml = {};137         s = jQuery.extend({}, jQuery.ajaxSettings, s);138         if (window.ActiveXObject) {139             var upload = new jQuery.ajaxUpload(s, xml);140             upload.start();141 142         } else {143             var id = new Date().getTime();144             var form = jQuery.createUploadForm(id, s.url, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));145             var io = jQuery.createUploadIframe(id, s.secureuri);146             var frameId = 'jUploadFrame' + id;147             var formId = 'jUploadForm' + id;148             // Watch for a new set of requests  149             if (s.global && !jQuery.active++) {150                 jQuery.event.trigger("ajaxStart");151             }152             var requestDone = false;153 154             if (s.global)155                 jQuery.event.trigger("ajaxSend", [xml, s]);156             // Wait for a response to come back  157             var uploadCallback = function (isTimeout) {158                 var io = document.getElementById(frameId);159 160                 try {161                     if (io.contentWindow) {162                         xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;163                         xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;164 165                     } else if (io.contentDocument) {166                         xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;167                         xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;168                     }169                 } catch (e) {170                     jQuery.handleError(s, xml, null, e);171                 }172                 if (xml || isTimeout == "timeout") {173                     requestDone = true;174                     var status;175                     try {176                         status = isTimeout != "timeout" ? "success" : "error";177                         // Make sure that the request was successful or notmodified  178                         if (status != "error") {179                             // process the data (runs the xml through httpData regardless of callback)  180                             var data = jQuery.uploadHttpData(xml, s.dataType);181                             // If a local callback was specified, fire it and pass it the data  182 183                             if (s.success)184                                 s.success(data, status);185 186                             // Fire the global callback  187                             if (s.global)188                                 jQuery.event.trigger("ajaxSuccess", [xml, s]);189                             if (s.complete)190                                 s.complete(data, status);191 192                         } else193                             jQuery.handleError(s, xml, status);194                     } catch (e) {195                         status = "error";196                         jQuery.handleError(s, xml, status, e);197                     }198 199                     // The request was completed  200                     if (s.global)201                         jQuery.event.trigger("ajaxComplete", [xml, s]);202                     // Handle the global AJAX counter  203                     if (s.global && ! --jQuery.active)204                         jQuery.event.trigger("ajaxStop");205 206                     // Process result  207                     jQuery(io).unbind();208 209                     setTimeout(function () {210                         try {211                             jQuery(io).remove();212                             jQuery(form).remove();213 214                         } catch (e) {215                             jQuery.handleError(s, xml, null, e);216                         }217 218                     }, 100);219 220                     xml = null;221 222                 }223             };224             // Timeout checker  225             if (s.timeout > 0) {226                 setTimeout(function () {227                     // Check to see if the request is still happening  228                     if (!requestDone) uploadCallback("timeout");229                 }, s.timeout);230             }231 232             try {233 234                 var form = jQuery('#' + formId);235                 jQuery(form).attr('action', s.url);236                 jQuery(form).attr('method', 'POST');237                 jQuery(form).attr('target', frameId);238 239                 if (form.encoding) {240                     jQuery(form).attr('encoding', 'multipart/form-data');241                 }242                 else {243                     jQuery(form).attr('enctype', 'multipart/form-data');244                 }245 246 247                 jQuery(form).submit();248 249             } catch (e) {250                 jQuery.handleError(s, xml, null, e);251             }252 253             jQuery('#' + frameId).load(uploadCallback);254             return { abort: function () { } };255 256         }257     },258 259     uploadHttpData: function (r, type) {260 261         var data = !type;262         data = type == "xml" || data ? r.responseXML : r.responseText;263         // If the type is "script", eval it in global context  264         if (type == "script")265             jQuery.globalEval(data);266         // Get the JavaScript object, if JSON is used.  267         if (type == "json") {268 269             //eval("data = " + $(data).html());//默认方式,在ie下不好使270             //data = jQuery.parseJSON(jQuery(data).text());//第一次修改后,ie7、8、9、10可用,ie11不可用271             try {272                 data = jQuery.parseJSON(data); //第二次修改,ie全兼容273             } catch (e) {274                 data = jQuery.parseJSON(jQuery(data).text());275             }276 277         }278         // evaluate scripts within html  279         if (type == "html")280             jQuery("<div>").html(data).evalScripts();281 282         return data;283     }284 }); 
复制代码

第三步:index.js代码

复制代码
 1 function fnExcelUpload(event) { 2     /// <summary>上传Excel</summary> 3     /// <param name="event" type="Object">file对象</param> 4     fnPushMainTr(); 5  6     $.ajaxFileUpload({ 7         url: "Service.ashx?Type=Upload", 8         secureuri: false, // 一般设置为false   9         fileElementId: "excel_upload", // 文件上传表单的id <input type="file" id="fileUpload" name="file" />  10         dataType: 'json', // 返回值类型 一般设置为json  11         success: function (data) {12             if (!data || data.reuslt == 'error' || data.result == 'warning') {13                 fnErrorMsg(data);14                 return;15             }16             //设置上传Excel按钮样式17             $('#btn-upload').removeClass('exl-submit-can').addClass('exl-submit-no').children('input').attr('disabled', true);18             //设置第一步的样式,并增加文字提示“完成”19             $('#step_one').removeClass('step-one-a').addClass('step-one-b').siblings('p:last').addClass('fc-green').children('span').text('完成')20                 .parents('li').addClass('fc-green');21             $('#loading_info').html('<span class="progress">Excel格式校验进行中</span>');22             setTimeout(function () {23                 fnGetState();24             }, 1000);25 26         },27         error: function (data)// 服务器响应失败处理函数  28         {29             console.log("服务器异常");30         }31     });32 }
复制代码

注:使用ajaxFileUpload.js上传excel文件时,在ie9以上会弹出下载窗口,ie7/8会报错缺少“)”,这是因为服务端返回的数据是json,ie无法解析导致的,

  如果之前是application/json的话就会弹出下载窗口,需要将服务器响应头修改为:Content-Type:text/html;charset=UTF-8即可

阅读全文
0 0
原创粉丝点击