AjaxFileUploaderV2.1修改版

AjaxFileUploaderV2.1修改版主要修复以下BUG:
1.高版本jquery没有handleError函数的出错处理.
2.对于服务器响应的ContentType不同设置可能会包含多余的pre标签出错处理.
3.对于发请求的dataType设为html出错的处理.
4.对于textarea字段(值含有双引号等特殊字符号时,发现值会被截取)出错的处理.
5.不能同时上传多个文件.


1.jquery1.5.0开始移除了handleError函数.
处理:如果高版本的jquery没有handleError,就添加扩展,否则就重写覆盖低版本的handleError.
做法:从jquery1.2.1(作者开发所需的jquery最低版本)复制handleError函数到ajaxfileupload.js,为jquery添加扩展.


2.对于服务器响应的ContentType不同设置可能会包含多余的pre标签.
处理:如果包含多余的pre标签,就要除掉
做法: 将io.contentWindow.document.body.innerHTML改成jQuery('<div>').html(io.contentWindow.document.body.innerHTML).text()
注:firefox没有innerText,否则改为io.contentWindow.document.body.innerText就OK


3.jquery低版本与高版本都没有evalScripts函数.在jquery1.1.4源码有以下注释This method no longer does anything - all script evaluation is taken care of within the HTML injection methods.作者应该从安全方面考虑,删除脚本.
处理:虽然可以从jquery1.1复制过来,但从注释来看,简单处理一下就OK

做法:将jQuery("<div>").html(data).evalScripts();改为jQuery("<div>").html(data).find('script').remove();


4.这问题首先要理解AjaxFileUploader的底层,通过iframe创建一个可上传文件的form,其中ajaxFileUpload的data都会被转成类型为hidden的input,也正是这种转换引起了问题.

处理:对于值含有双引号的字段,应使用textarea,而不是使用hidden的input.(只想出此方法,或许有人可以想出更完美的方法)

做法:

a:修改createUploadForm函数,增加第四个参数textareas,并在处理完data数据转换后加入如下代码:

        if (textareas) {
            for (var i in textareas) {
                jQuery('<textarea name="' + i + '">'+textareas[i]+'</textarea>').appendTo(form);
            }
        }

b.调用createUploadForm的地方由jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data) == 'undefined' ? false : s.data))改为jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data) == 'undefined' ? false : s.data),(typeof(s.textareas) == 'undefined' ? false : s.textareas))

c.最后创建时,下面是一个例子:

                var obj = {
                    "id": 456,
                    "password": "13131"
                };
                var textareas={
                    "content": $("#content").val()
                };
                $.ajax()
                $.ajaxFileUpload({
                    url:"user/save",
                    type: "POST",
                    secureuri: false,
                    fileElementId: 'bgFileToUpload',
                    data: obj,
                    textareas:textareas,
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                    }
                });

如果将上面的data不用hidden的input,都统一使用textarea,那么就不必要加入第四个参数textareas,外部创建请求调用时也方便.

5.想处理多个上传文件.就要修改源码对fileElementId的处理就可以了.

处理与做法:将上传文件的部分改成for循环.

        if(typeof(fileElementId)=="string"){
            fileElementId=[fileElementId];
        }
        for(var i in fileElementId) {
            var oldElement = jQuery('#' + fileElementId[i]);
            var newElement = jQuery(oldElement).clone();
            jQuery(oldElement).attr('id', fileId);
            jQuery(oldElement).before(newElement);
            jQuery(oldElement).appendTo(form);
        }

最改后的源码:

jQuery.extend({
    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>');
        //Handle files
        if(typeof(fileElementId)=="string"){
            fileElementId=[fileElementId];
        }
        for(var i in fileElementId) {
            var oldElement = jQuery('#' + fileElementId[i]);
            var newElement = jQuery(oldElement).clone();
            jQuery(oldElement).attr('id', fileId);
            jQuery(oldElement).before(newElement);
            jQuery(oldElement).appendTo(form);
        }
        //Handle data
        if (data) {
            for (var i in data) {
                jQuery('<textarea name="' + i + '" style="display:none;">'+data[i]+'</textarea>').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) {
        // 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 ? jQuery('<div>').html(io.contentWindow.document.body.innerHTML).text(): null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
                } else if (io.contentDocument) {
                    xml.responseText = io.contentWindow.document.body ? jQuery('<div>').html(io.contentWindow.document.body.innerHTML).text(): 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);
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).find('script').remove();
        return data;
    },
    handleError: function( s, xml, status, e ) {
        // If a local callback was specified, fire it
        if ( s.error )
            s.error( xml, status, e );
        // Fire the global callback
        if ( s.global )
            jQuery.event.trigger( "ajaxError", [xml, s, e] );
    }
});

源码:http://download.csdn.net/detail/xiejx618/8666001

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值