一、ajaxFileUpload是一個異步上傳文件的jQuery插件。
傳一個不知道什么版本的上來,以后不用到處找了。
語法:$.ajaxFileUpload([options])
options參數說明:
1、url 上傳處理程序地址。
2,fileElementId 需要上傳的文件域的ID,即<input type="file">的ID。
3,secureuri 是否啟用安全提交,默認為false。
4,dataType 服務器返回的數據類型。可以為xml,script,json,html。如果不填寫,jQuery會自動判斷。
5,success 提交成功后自動執行的處理函數,參數data就是服務器返回的數據。
6,error 提交失敗自動執行的處理函數。
7,data 自定義參數。這個東西比較有用,當有數據是與上傳的圖片相關的時候,這個東西就要用到了。
8, type 當要提交自定義參數時,這個參數要設置成post
錯誤提示:
1,SyntaxError: missing ; before statement錯誤
如果出現這個錯誤就需要檢查url路徑是否可以訪問
2,SyntaxError: syntax error錯誤
如果出現這個錯誤就需要檢查處理提交操作的服務器后台處理程序是否存在語法錯誤
3,SyntaxError: invalid property id錯誤
如果出現這個錯誤就需要檢查文本域屬性ID是否存在
4,SyntaxError: missing } in XML expression錯誤
如果出現這個錯誤就需要檢查文件name是否一致或不存在
5,其它自定義錯誤
大家可使用變量$error直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多。
使用方法:
第一步:先引入jQuery與ajaxFileUpload插件。注意先后順序,這個不用說了,所有的插件都是這樣。
<script src="jquery-1.7.1.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script>
第二步:HTML代碼:
<body> <p><input type="file" id="file1" name="file" /></p> <input type="button" value="上傳" /> <p><img id="img1" alt="上傳成功啦" src="" /></p> </body>
第三步:JS代碼
<script src="jquery-1.7.1.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $(":button").click(function () { ajaxFileUpload(); }) }) function ajaxFileUpload() { $.ajaxFileUpload ( { url: '/upload.aspx', //用於文件上傳的服務器端請求地址 secureuri: false, //是否需要安全協議,一般設置為false fileElementId: 'file1', //文件上傳域的ID dataType: 'json', //返回值類型 一般設置為json success: function (data, status) //服務器成功響應處理函數 { $("#img1").attr("src", data.imgurl); if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); } } }, error: function (data, status, e)//服務器響應失敗處理函數 { alert(e); } } ) return false; } </script>
ajaxfileupload.js
jQuery.extend({ handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; if(window.ActiveXObject) { if(typeof uri== 'boolean'){ iframeHtml += ' src="' + 'javascript:false' + '"'; } else if(typeof uri== 'string'){ iframeHtml += ' src="' + uri + '"'; } } iframeHtml += ' />'; jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0); }, createUploadForm: function(id, fileElementId, data) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); if(data) { for(var i in data) { jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); } } var oldElement = jQuery('#' + fileElementId); var newElement = jQuery(oldElement).clone(true); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); //set attributes jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data)); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try { jQuery(io).remove(); jQuery(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try { var form = jQuery('#' + formId); jQuery(form).attr('action', s.url); jQuery(form).attr('method', 'POST'); jQuery(form).attr('target', frameId); if(form.encoding) { jQuery(form).attr('encoding', 'multipart/form-data'); } else { jQuery(form).attr('enctype', 'multipart/form-data'); } jQuery(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } jQuery('#' + frameId).load(uploadCallback ); return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) //eval( "data = " + data); eval("data = " "+data+" " "); // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); return data; } })
代碼其實很簡單,但是如果你為了做兼容IE7+以上的瀏覽器,坑還是不少的
1.就是作為文件域(<input type="file">)必須要有name屬性,如果沒有name屬性,上傳之后服務器是獲取不到圖片的。如:正確的寫法是<input type="file" id="file1" name="file1" />
2.最經典的錯誤終於找到原因所在了。Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError',這個是google瀏覽器報的錯誤,非常經典, 不知道是我的版本問題還是真正存在的問題。這個問題的根源經過N次上傳才找到問題的根本所在。答案是:dataType參數一定要大寫。如:dataType: 'HTML'。
3.模擬點擊文本域在IE7上無效,最好用CSS 透明度解決
附帶一個問題匯總的地址:http://blog.yadgen.com/?p=970
