1. 程式人生 > >jQuery插件ajaxfileupload.js源碼與使用

jQuery插件ajaxfileupload.js源碼與使用

eid part tar pos reg file com 阻止提交 move

在網頁應用中,一般會用到上傳文件或者圖片什麽的到服務器,那麽可以用ajaxfileupload.js,但是在使用ajaxfileupload.js時候,當服務器返回的json帶有&符號的時候,返回的data數據裏面所有的&被轉義成了&
下面的ajaxfileupload.js是經過修改的文件上傳庫。

jQuery.extend({
    /** createUploadIframe 創建上傳的iframe
     * @param id 傳遞當前系統的時間字符串
     * @param uri 傳入的json對象的一個參數
     * */
    createUploadIframe: 
function (id, uri) { //iframe添加一個id var frameId = ‘jUploadFrame‘ + id; //創建iframe元素 var iframeHtml = ‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" style="position:absolute; top:-9999px; left:-9999px"‘; if (window.ActiveXObject) {//判斷瀏覽器是否支持ActiveX控件 if
(typeof uri == ‘boolean‘) { //阻止提交數據 iframeHtml += ‘ src="‘ + ‘javascript:false‘ + ‘"‘; } else if (typeof uri == ‘string‘) { iframeHtml += ‘ src="‘ + uri + ‘"‘; } } iframeHtml += ‘ />‘;
//將動態iframe追加到body中 jQuery(iframeHtml).appendTo(document.body); //返回iframe對象 return jQuery(‘#‘ + frameId).get(0); }, /** createUploadForm 創建form * @param id 當前系統時間字符串 * @param fileElementId 為頁面input type=‘file‘的id * @param data 向服務器傳遞的值 如 data:{key1:value1,key2:value2} * */ createUploadForm: function (id, fileElementId, data) { //給form添加id var formId = ‘jUploadForm‘ + id; //給type為file的上傳按鈕添加id var fileId = ‘jUploadFile‘ + id; //創建form元素 var form = jQuery(‘<form action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data" ></form>‘); if (data) { for (var i in data) { //根據data提交的數據,創建隱藏域 jQuery(‘<input type="hidden" name="‘ + i + ‘" value="‘ + data[i] + ‘" />‘).appendTo(form); } } //得到頁面中的<input type=‘file‘ />對象 if (typeof(fileElementId) == ‘string‘) { fileElementId = fileElementId.split(‘,‘); } for (var i=0,j = fileElementId.length;i < j; i++) { var oldElement = jQuery(‘#‘ + fileElementId[i]); //克隆頁面中的<input type=‘file‘ />對象 var newElement = jQuery(oldElement).clone(true); //修改原對象的id jQuery(oldElement).attr(‘id‘, fileId); //在原對象前插入克隆對象 jQuery(oldElement).before(newElement); //把原對象插入到動態form的結尾處 jQuery(oldElement).appendTo(form); } //給動態form添加樣式 jQuery(form).css(‘position‘, ‘absolute‘); jQuery(form).css(‘top‘, ‘-1200px‘); jQuery(form).css(‘left‘, ‘-1200px‘); jQuery(form).appendTo(‘body‘); return form; }, /** ajaxFileUpload ajax上傳請求 * @param s 傳入一些ajax的參數 * */ ajaxFileUpload: function (s) { s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime(); //創建動態form var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == ‘undefined‘ ? false : s.data)); //創建動態iframe s.secureuri 是否需要安全協議,一般置為false var io = jQuery.createUploadIframe(id, s.secureuri); //動態iframe的id var frameId = ‘jUploadFrame‘ + id; //動態form的id var formId = ‘jUploadForm‘ + id; //當jQuery開始一個ajax請求時發生,global表示是否觸發全局ajax事件,默認是true; if (s.global && !jQuery.active++) { //觸發ajaxStart方法 jQuery.event.trigger("ajaxStart"); } //請求完成標誌 var requestDone = false; // 創建請求對象 var xml = {}; if (s.global){ //觸發ajaxSend方法 jQuery.event.trigger("ajaxSend", [xml, s]); } //回調函數 var uploadCallback = function (isTimeout) { //得到iframe對象 var io = document.getElementById(frameId); try { //動態iframe所在窗口對象是否存在 if (io.contentWindow) { if(s.dataType==‘text‘){ xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.textContent : null; }else{ 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; } //動態iframe的文檔對象是否存在 else if (io.contentDocument) { if(s.dataType==‘text‘){ xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.textContent : null; }else{ xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; } 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); } //xml變量被賦值或者isTimeout == "timeout"都表示請求發出,並且有響應 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); } if (s.global){ // The request was completed jQuery.event.trigger("ajaxComplete", [xml, s]); } if (s.global && ! --jQuery.active){ jQuery.event.trigger("ajaxStop"); } if (s.complete){ s.complete(xml, status); } //移除iframe的事件處理程序 jQuery(io).unbind(); setTimeout(function () {//設置超時時間 try { //移除動態iframe與動態form jQuery(io).remove(); jQuery(form).remove(); }catch (e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } //超時檢測 if (s.timeout > 0) { setTimeout(function () { //如果請求仍未完成,就發送超時信號 if (!requestDone) uploadCallback("timeout"); }, s.timeout); } try { var form = jQuery(‘#‘ + formId); jQuery(form).attr(‘action‘, s.url);//傳入的ajax頁面導向url jQuery(form).attr(‘method‘, ‘POST‘);//設置提交表單方式 jQuery(form).attr(‘target‘, frameId);//返回的目標iframe,就是創建的動態iframe if (form.encoding) { //選擇編碼方式 jQuery(form).attr(‘encoding‘, ‘multipart/form-data‘); }else { jQuery(form).attr(‘enctype‘, ‘multipart/form-data‘); } jQuery(form).submit();//提交form表單 }catch (e) { jQuery.handleError(s, xml, null, e); } jQuery(‘#‘ + frameId).load(uploadCallback); //ajax 請求從服務器加載數據,同時傳入回調函數 return { abort: function () { } }; }, uploadHttpData: function (r, type) { var data = !type; // If the type is "script", eval it in global context data = type == "xml" || data ? r.responseXML : r.responseText; if (type == "script"){ jQuery.globalEval(data); } // Get the JavaScript object, if JSON is used. if (type == "json"){ eval("data = " + data); } if (type == "html"){ jQuery("<div>").html(data).evalScripts(); } return data; }, 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] ); } } })

下面是調用方式:

$.ajaxFileUpload({
    url: ‘ps.php‘,
    //一般設置為false
    secureuri: false,           
    data:{
        email:email
    },
    //文件上傳控件的id屬性
    fileElementId: $("input#xxx").attr("id"), 
    //返回值類型 一般設置為json,但是如果返回的數據有&等特殊符號,這兒改成text
    dataType: ‘text‘,
    success: function (data, status)  {
        //如果dataType為text,那麽這兒需要把返回的字符串轉成對象
        data = JSON.parse(data);
    },
    error: function (data, status, e){
        console.log(e);
    }
 })

註:如果有&符號返回,這dataType改成text,然後把返回的data字符串通過JSON.parse()處理。
參考地址:http://www.oschina.net/code/snippet_105637_50057

jQuery插件ajaxfileupload.js源碼與使用