Ajax文件上传插件很多,但兼容性各不一样,许多是对ie不兼容的,另外项目中是要求将网页内容嵌入到桌面端应用的,这样就不允许带flash的上传插件了,如:jquery uploadify。。。悲剧
对于Ajax文件上传,大体是有:
1、创建一个input type="file" 的文件上传按钮,根据其id监听绑定其change事件,在事件中用jquery创建一个iframe,嵌入添加隐藏form,同时创建input type="file",id相同的文件上传按钮,并传入其他需要提交的数据,然后提交,提交完成后移除一个input type="file",这样用bind或on的绑定就对新的input 框失效,需要重新再绑定一次change事件,以前的jquery是可以使用live函数代替的,现在只能在文件上传成功后再绑定一次change事件。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 $(function() { 2 uploadFile("fileData",'cn.ftiao.cm.model.LiveCourse','',"CI"); 3 }); 4 5 function uploadFile(id,classFullName,jsonStrValue,preFileName){ 6 $("#"+id).on("change", function(){ 7 // 上传方法 8 $.ajaxFileUpload({ 9 url:$("#"+id).attr("data-url-upload"), //需要链接到服务器地址 10 secureuri:false, 11 type:"post", 12 fileElementId:id, //文件选择框的id属性 13 dataType: 'json', 14 data:{ 15 "classFullName":classFullName, 16 "jsonStrValue":"", 17 "preFileName":preFileName 18 }, 19 //服务器返回的格式,可以是json 20 success: function (data, status){ //相当于java中try语句块的用法 21 $("#courseIconImg").attr("src",$(".ctx").val()+"/images/img-class.png"); 22 alert("hello"); 23 //先将原有的上传展示清除 24 $("#" + id).nextAll("span").remove(); 25 $("#courseIcon").val(data.outputFileName); 26 // $("#coursewareFile").val(data.outputFileName); 27 var uploadHtml = "<span id='"+data.outputPreFileName+"_livelesson_div' style='color:#FFFFFF;'>"; 28 uploadHtml += data.fileUploadName ; 29 uploadHtml += "<a name='_LIVELESSON_PRIVIEW'> 预览 </a><a name='_LIVELESSON_DEL'> 删除 </a>"; 30 uploadHtml += "</span>"; 31 // $("#"+id).parents("li").append(uploadHtml); 32 uploadFile("fileData",'cn.ftiao.cm.model.LiveCourse','',"CI"); 33 }, 34 error: function (data, status, e) //相当于java中catch语句块的用法 35 { 36 alert(e); 37 } 38 }); 39 }); 40 return false; 41 }
2、创建一个 input type="file"的按钮,监听其click事件,然后创建iframe,隐藏form,隐藏form里有个 input type="file"的文件上传框,模拟点击click,弹出文件选择框,选择完文件后上传。此方法在ie下会报 “权限不足” 问题。
下面是ajaxFileUpload 插件
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 jQuery.extend({ 2 3 handleError: function(s, xhr, status, e) { 4 // If a local callback was specified, fire it 5 if (s.error) { 6 s.error.call(s.context || window, xhr, status, e); 7 } 8 9 // Fire the global callback 10 if (s.global) { 11 (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]); 12 } 13 }, 14 createUploadIframe: function(id, uri) 15 { 16 //create frame 17 var frameId = 'jUploadFrame' + id; 18 var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; 19 if(window.ActiveXObject) 20 { 21 if(typeof uri== 'boolean'){ 22 iframeHtml += ' src="' + 'javascript:false' + '"'; 23 24 } 25 else if(typeof uri== 'string'){ 26 iframeHtml += ' src="' + uri + '"'; 27 28 } 29 } 30 iframeHtml += ' />'; 31 jQuery(iframeHtml).appendTo(document.body); 32 33 return jQuery('#' + frameId).get(0); 34 }, 35 createUploadForm: function(id, fileElementId, data) 36 { 37 //create form 38 var formId = 'jUploadForm' + id; 39 var fileId = 'jUploadFile' + id; 40 var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); 41 if(data) 42 { 43 for(var i in data) 44 { 45 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); 46 } 47 } 48 var oldElement = jQuery('#' + fileElementId); 49 var newElement = jQuery(oldElement).clone(); 50 jQuery(oldElement).attr('id', fileId); 51 jQuery(oldElement).before(newElement); 52 jQuery(oldElement).appendTo(form); 53 54 55 56 //set attributes 57 jQuery(form).css('position', 'absolute'); 58 jQuery(form).css('top', '-1200px'); 59 jQuery(form).css('left', '-1200px'); 60 jQuery(form).appendTo('body'); 61 return form; 62 }, 63 64 ajaxFileUpload: function(s) { 65 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout 66 s = jQuery.extend({}, jQuery.ajaxSettings, s); 67 var id = new Date().getTime() 68 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data)); 69 var io = jQuery.createUploadIframe(id, s.secureuri); 70 var frameId = 'jUploadFrame' + id; 71 var formId = 'jUploadForm' + id; 72 // Watch for a new set of requests 73 if ( s.global && ! jQuery.active++ ) 74 { 75 jQuery.event.trigger( "ajaxStart" ); 76 } 77 var requestDone = false; 78 // Create the request object 79 var xml = {} 80 if ( s.global ) 81 jQuery.event.trigger("ajaxSend", [xml, s]); 82 // Wait for a response to come back 83 var uploadCallback = function(isTimeout) 84 { 85 var io = document.getElementById(frameId); 86 try 87 { 88 if(io.contentWindow) 89 { 90 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; 91 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; 92 93 }else if(io.contentDocument) 94 { 95 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; 96 xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; 97 } 98 }catch(e) 99 { 100 jQuery.handleError(s, xml, null, e); 101 } 102 if ( xml || isTimeout == "timeout") 103 { 104 requestDone = true; 105 var status; 106 try { 107 status = isTimeout != "timeout" ? "success" : "error"; 108 // Make sure that the request was successful or notmodified 109 if ( status != "error" ) 110 { 111 // process the data (runs the xml through httpData regardless of callback) 112 var data = jQuery.uploadHttpData( xml, s.dataType ); 113 // If a local callback was specified, fire it and pass it the data 114 if ( s.success ) 115 s.success( data, status ); 116 117 // Fire the global callback 118 if( s.global ) 119 jQuery.event.trigger( "ajaxSuccess", [xml, s] ); 120 } else 121 jQuery.handleError(s, xml, status); 122 } catch(e) 123 { 124 status = "error"; 125 jQuery.handleError(s, xml, status, e); 126 } 127 128 // The request was completed 129 if( s.global ) 130 jQuery.event.trigger( "ajaxComplete", [xml, s] ); 131 132 // Handle the global AJAX counter 133 if ( s.global && ! --jQuery.active ) 134 jQuery.event.trigger( "ajaxStop" ); 135 136 // Process result 137 if ( s.complete ) 138 s.complete(xml, status); 139 140 jQuery(io).unbind() 141 142 setTimeout(function() 143 { try 144 { 145 jQuery(io).remove(); 146 jQuery(form).remove(); 147 148 } catch(e) 149 { 150 jQuery.handleError(s, xml, null, e); 151 } 152 153 }, 100) 154 155 xml = null 156 157 } 158 } 159 // Timeout checker 160 if ( s.timeout > 0 ) 161 { 162 setTimeout(function(){ 163 // Check to see if the request is still happening 164 if( !requestDone ) uploadCallback( "timeout" ); 165 }, s.timeout); 166 } 167 try 168 { 169 170 var form = jQuery('#' + formId); 171 jQuery(form).attr('action', s.url); 172 jQuery(form).attr('method', 'POST'); 173 jQuery(form).attr('target', frameId); 174 if(form.encoding) 175 { 176 jQuery(form).attr('encoding', 'multipart/form-data'); 177 } 178 else 179 { 180 jQuery(form).attr('enctype', 'multipart/form-data'); 181 } 182 jQuery(form).submit(); 183 184 } catch(e) 185 { 186 jQuery.handleError(s, xml, null, e); 187 } 188 189 jQuery('#' + frameId).load(uploadCallback ); 190 return {abort: function () {}}; 191 192 }, 193 194 uploadHttpData: function( r, type ) { 195 var data = !type; 196 data = type == "xml" || data ? r.responseXML : r.responseText; 197 // If the type is "script", eval it in global context 198 if ( type == "script" ) 199 jQuery.globalEval( data ); 200 // Get the JavaScript object, if JSON is used. 201 if (type == "json"){ 202 if (data.indexOf("<") >= 0) { 203 data = jQuery.parseJSON(jQuery(data).text()); 204 } 205 else { 206 eval("data = " + data); /*Bug fixed by under */ 207 } 208 } 209 // evaluate scripts within html 210 if ( type == "html" ) 211 jQuery("<div>").html(data).evalScripts(); 212 213 return data; 214 } 215 })