歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery 關於ajaxfileupload.js插件的逐步解析(ajaxfileupload.js第二彈)

jQuery 關於ajaxfileupload.js插件的逐步解析(ajaxfileupload.js第二彈)

日期:2017/3/1 9:40:16   编辑:Linux編程

如果你看了上一篇《ASP.NET 使用js插件出現上傳較大文件失敗的解決方法(ajaxfileupload.js第一彈) http://www.linuxidc.com/Linux/2014-09/106412.htm》的話,應該就知道我是逼不得已要認真學習下ajaxfileupload.js這個上傳文件插件的。哈哈,開個玩笑啦,其實學習是給自己學的,而且學會了真的是很享受的~

這篇呢,就是想把這個插件的思路說一下,其中中文注解是我寫的,英文注解應該是原作者寫的吧~說實話,有些if判斷裡的東西我也沒太弄明白,但是大致思路還是OK的。


jQuery.extend({

createUploadIframe: function (id, uri) {//id為當前系統時間字符串,uri是外部傳入的json對象的一個參數

//create frame

var frameId = 'jUploadFrame' + id; //給iframe添加一個獨一無二的id

var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" '; //創建iframe元素

if (window.ActiveXObject) {//判斷浏覽器是否支持ActiveX控件

if (typeof uri == 'boolean') {

iframeHtml += ' src=\'#\'" />';

jQuery(iframeHtml).appendTo(document.body); //將動態iframe追加到body中

return jQuery('#' + frameId).get(0); //返回iframe對象

},

createUploadForm: function (id, fileElementId, data) {//id為當前系統時間字符串,fileElementId為頁面<input type='file' />的id,data的值需要根據傳入json的鍵來決定

//create form

var formId = 'jUploadForm' + id; //給form添加一個獨一無二的id

var fileId = 'jUploadFile' + id; //給<input type='file' />添加一個獨一無二的id

var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //創建form元素

if (data) {//通常為false

for (var i in data) {

jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根據data的內容,創建隱藏域,這部分我還不知道是什麼時候用到。估計是傳入json的時候,如果默認傳一些參數的話要用到。

}

}

var oldElement = jQuery('#' + fileElementId); //得到頁面中的<input type='file' />對象

var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />對象

jQuery(oldElement).attr('id', fileId); //修改原對象的id

jQuery(oldElement).before(newElement); //在原對象前插入克隆對象

jQuery(oldElement).appendTo(form); //把原對象插入到動態form的結尾處

//set attributes

jQuery(form).css('position', 'absolute'); //給動態form添加樣式,使其浮動起來,

jQuery(form).css('top', '-1200px');

jQuery(form).css('left', '-1200px');

jQuery(form).appendTo('body'); //把動態form插入到body中

return form;

},

ajaxFileUpload: function (s) {//這裡s是個json對象,傳入一些ajax的參數

// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout

s = jQuery.extend({}, jQuery.ajaxSettings, s); //此時的s對象是由jQuery.ajaxSettings和原s對象擴展後的對象

var id = new Date().getTime(); //取當前系統時間,目的是得到一個獨一無二的數字

var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //創建動態form

var io = jQuery.createUploadIframe(id, s.secureuri); //創建動態iframe

var frameId = 'jUploadFrame' + id; //動態iframe的id

var formId = 'jUploadForm' + id; //動態form的id

// Watch for a new set of requests

if (s.global && !jQuery.active++) {//當jQuery開始一個ajax請求時發生

jQuery.event.trigger("ajaxStart"); //觸發ajaxStart方法

}

var requestDone = false; //請求完成標志

// Create the request object

var xml = {};

if (s.global)

jQuery.event.trigger("ajaxSend", [xml, s]); //觸發ajaxSend方法

// Wait for a response to come back

var uploadCallback = function (isTimeout) {//回調函數

var io = document.getElementById(frameId); //得到iframe對象

try {

if (io.contentWindow) {//動態iframe所在窗口對象是否存在

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) {//動態iframe的文檔對象是否存在

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") {//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); //根據傳送的type類型,返回json對象,此時返回的data就是後台操作後的返回結果

// 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();//移除iframe的事件處理程序

setTimeout(function () {//設置超時時間

try {

jQuery(io).remove();//移除動態iframe

jQuery(form).remove();//移除動態form

} 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);//傳入的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;

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);

// evaluate scripts within html

if (type == "html")

jQuery("<div>").html(data).evalScripts();

return data;

}

})

ajaxfileupload.js插件大致的思路就是如上所述,但是對於ajax來說,傳值也是相當關鍵的部分,也就是傳入的json對象裡的鍵值對。

調用方法如下:


$.ajaxFileUpload

(

{

url: '../../XXXX/XXXX.aspx', //用於文件上傳的服務器端請求地址

secureuri: false, //一般設置為false

fileElementId: $("input#xxx").attr("id"), //文件上傳控件的id屬性 <input type="file" id="file" name="file" /> 注意,這裡一定要有name值

//$("form").serialize(),表單序列化。指把所有元素的ID,NAME 等全部發過去

dataType: 'json',//返回值類型 一般設置為json

complete: function () {//只要完成即執行,最後執行

},

success: function (data, status) //服務器成功響應處理函數

{

if (typeof (data.error) != 'undefined') {

if (data.error != '') {

if (data.error == "1001") {//這個error(錯誤碼)是由自己定義的,根據後台返回的json對象的鍵值而判斷

}

else if (data.error == "1002") {

}

alert(data.msg);//同error

return;

} else {

alert(data.msg);

}

}

/*

* 這裡就是做一些其他操作,比如把圖片顯示到某控件中去之類的。

*/

},

error: function (data, status, e)//服務器響應失敗處理函數

{

alert(e);

}

}

)

整個就是使用ajaxfileupload.js插件的大致方法。當然,明白其工作原理越透徹,我們也就能越好的去操作和使用它。

以上的分析希望對剛接觸ajaxfileupload.js插件的朋友們有幫助。

還有最後一彈,如有感興趣的朋友,請關注:

jQuery 自制上傳頭像插件-附帶Demo實例(ajaxfileupload.js第三彈) http://www.linuxidc.com/Linux/2014-09/106414.htm

Copyright © Linux教程網 All Rights Reserved