附博主正在使用的ajaxfileupload.js

不保证所有人都不会出问题,仅博主目前使用未曾遇见问题。
文件下载:ajaxfileupload.js(右键另存为)

jQuery.extend({
    createUploadIframe: function(id, uri)
    {
            //create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" style="position: absolute; top: -9999px; left: -9999px;" src="' + uri + '" name="' + frameId + '">';
            jQuery(iframeHtml).appendTo(document.body);

            return jQuery('#' + frameId).get(0);            
    },
    createUploadForm: function(id, fileElementId)
    {
        //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>

');    
        var oldElement = jQuery('#' + fileElementId);
        var newElement = jQuery(oldElement).clone();
        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);
        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 &amp;&amp; ! jQuery.active++ )
        {
            jQuery.event.trigger( "ajaxStart" );
        }            
        var requestDone = false;
        // Create the request object
        var xml = {};
        if ( s.global )
            jQuery.event.trigger("ajaxSend", );
        // 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",  );
                    } 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",  );

                // Handle the global AJAX counter
                if ( s.global &amp;&amp; ! --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 &gt; 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 () {}}; 

    },

    // handleError 方法在jquery1.4.2之后移除了,此处重写改方法
    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] );
        }
    },

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

</div>
</iframe>

ajaxfileupload.js问题汇总及解决 附修复版下载

使用Jquery做上传文件处理时,用到了ajaxfileupload.js 这个第三方代码,但是这个js几乎就是半成品,问题很多。现在整理如下并附修复版的ajaxfileupload.js下载。

问题:
1:无法带参数提交,只能上传文件;
2:运行时报:jQuery.handleError is not a function 错误;
3:执行成功后,始终指向error方法处理,无法执行sucess方法;

解决方法:
1:无法带参数提交,只能上传文件;
原作者一定是把这个代码当作练习来写的,只完成了文件提交这个功能。需要对代码做些许修改即可。有两处修改:
第一处是将原createUploadForm: function(id, fileElementId) 方法添加一个data参数,并将data中的数据拼接进去即可。代码如下:

createUploadForm: function(id, fileElementId,data) {
    //create form
    var formId = 'jUploadForm' + id;
    var fileId = 'jUploadFile' + id;
    var form = jQuery('');
    var oldElement = jQuery('#' + fileElementId);
    var newElement = jQuery(oldElement).clone();
    jQuery(oldElement).attr('id', fileId);
    jQuery(oldElement).before(newElement);
    jQuery(oldElement).appendTo(form); // 增加参数的支持
    if (data) {
        for (var i in data) 
        {
            $('').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;
};

 

第二处 是调用createUploadForm方法地方,如下所示:

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);
   var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
    
   var io = jQuery.createUploadIframe(id, s.secureuri);
   ...

2:运行时报:jQuery.handleError is not a function 错误;
这个错误是由于ajaxfileupload.js 是在jquery1.4.2版本之前写的,Jquery之后的版本已经没有了handleError 方法,所以可以将1.4.2版本中的该方法复制到该js中。

// handleError 方法在jquery1.4.2之后移除了,此处重写改方法
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] );
    }
},

3:执行成功后,始终指向error方法处理,无法执行sucess方法;
这个是由于ajaxfileupload.js 处理返回data的时候,没有考虑后台返回的是字符串的问题(即使返回的JSON格式数据,我们也大多喜欢转化为字符串来返回)。修改uploadHttpData方法:

// Get the JavaScript object, if JSON is used.
if ( type == "json" ){
    // 如果返回的是字符串(JSON格式字符串),下面会报错,导致无法走入sucess方法 加上"
    // eval( "data = " + data );
    eval("data = " "+data+" " ");
}

修复版ajaxfileupload.js 下载 :ajaxfileupload.js

JQuery ajaxfileupload 异步上传文件

JQuery ajaxfileupload 异步上传文件:

// 调用方法:
function ajaxFileUpload() {
    $.ajaxFileUpload({
        cache:false,
        url:url,
        secureuri:false,
        fileElementId:'user_file',
        dataType: 'json',
        success: function (result) {
            alert("上传成功");
        },
        error: function () {
            alert('图片上传失败');
        }
    });

    return true;
}
<input name="user_file" type="file" />

文件下载(右击另存为):ajaxfileupload.js