jQuery ajaxFileUpload

简介: jQuery ajaxFileUpload

今天做图片上传用ajaxFileUpload.js时遇到了一个错误提示:TypeError: $.ajaxFileUpload is not a function,下面给出解决办法!

ajaxFileUpload.js 很多同名的,因为做出来一个很容易。

AjaxFileUpload.js并不是一个很出名的插件,只是别人写好的放出来供大家用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。

 

下载地址就不贴了,下面直接给源码

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>');
        if (data) {
            for (var i in data) {
                if (data[i].name != null && data[i].value != null) {
                    jQuery('<input type="hidden" name="' + data[i].name + '" value="' + data[i].value + '" />').appendTo(form);
                } else {
                    jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(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 y 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;
        if (!type)
            data = r.responseText;
        if (type == "xml")
            data = r.responseXML;
        //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") {
            ////////////Fix the issue that it always throws the error "unexpected token ///////////////
            data = r.responseText;
            var start = data.indexOf(">");
            if (start != -1) {
                var end = data.indexOf("<", start + 1);
                if (end != -1) {
                    data = data.substring(start + 1, end);
                }
            }
            ///////////////////////////////////////////////////////////////////////////////////////////
            eval("data = " + data);
        }
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();
        return data;
    }
})

其实严格来说TypeError: $.ajaxFileUpload is not a function并不是一个真正的错误,这是jquery的版本问题,这个插件貌似只支持jquery1.4之前的版本,

为了让插件支持更高版本的jquery做了修改,将下列代码加入插件源文件即可

handleError: function (s, xhr, status, e) {  
        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]);
        }
    }

插件原本并不支持多图片上传,如果要支持多图片上传,修改如下

//将插件源文件内的这些代码
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//改成下面这样即可
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);
}

修改之后jQuery1.9以上会报错,(a.indexOf不是一个函数)

插件使用方法:

$.ajaxFileUpload([options])

  options参数说明:

1、url            上传处理程序地址。  

2,fileElementId       需要上传的文件域的ID,即<input type="file">的ID ;有多个input标签时,多个文件域的ID需要写成数组形式['file1ID','file2ID']。

3,secureuri        是否启用安全提交,默认为false。

4,dataType        服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。

5,success        提交成功后自动执行的处理函数,参数data就是服务器返回的数据。

6,error          提交失败自动执行的处理函数。

7,data           自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。

8, type            当要提交自定义参数时,这个参数要设置成post

 

 

最后提示一句,input的name属性一定要写.


相关文章
|
JavaScript
ajaxFileUpload 报错jQuery.handleError is not a function
ajaxFileUpload 报错jQuery.handleError is not a function
95 0
【转】JQuery插件ajaxFileUpload 异步上传文件(PHP版)
前几天想在手机端做个异步上传图片的功能,平时用的比较多的JQuery图片上传插件是Uploadify这个插件,效果很不错,但是由于手机不支持flash,所以不得不再找一个文件上传插件来用了。后来发现ajaxFileUpload这个插件挺不错,所以就用这个插件来做异步上传文件的效果。
1259 0
|
JavaScript 前端开发 PHP
AjaxFileUpload文件上传组件(php+jQuery+ajax)
jQuery插件AjaxFileUpload可以实现ajax文件上传,下载地址:http://www.phpletter.com/contents/ajaxfileupload/ajaxfileupload.
1117 0
|
JSON JavaScript 前端开发
jQuery插件之ajaxFileUpload(ajax文件上传)
一、ajaxFileUpload是一个异步上传文件的jQuery插件。   传一个不知道什么版本的上来,以后不用到处找了。   语法:$.ajaxFileUpload([options])   options参数说明: 1、url            上传处理程序地址。
2692 0
|
JavaScript 前端开发 PHP
jQuery插件AjaxFileUpload文件上传实现Javascript多文件上传功能
Ajax file upload plugin是一个功能强大的文件上传jQuery插件,可自定义链接、或其它元素庖代传统的file表单上传结果,可实现Ajax动态提示文件上传 过程,同时支撑多文件上传,AjaxFileUpload文件上传插件功能斗劲稳定,今朝应用也斗劲多,简单应用实例如下: 查看AjaxFileUpload相干jQuery官方文档介绍 AjaxFileUpload JS库
1587 0
|
JSON JavaScript 前端开发
|
JSON JavaScript Java
jquery之ajaxfileupload异步上传插件
点我下载工程代码由于项目需求,在处理文件上传时需要使用到文件的异步上传。这里使用Jquery Ajax File Uploader这个组件下载地址:http://www.phpletter.com/download_project_version.php?version_id=6服务器端采用struts2来处理文件上传。
1108 0
|
JavaScript 前端开发 PHP
jQuery插件AjaxFileUpload文件上传实现Javascript多文件上传功能
引用:http://cgxcn.blog.163.com/blog/static/1323124220095472652900/ Ajax file upload plugin是一个功能强大的文件上传jQuery插件,可自定义链接、图片或其它元素取代传统的file表单上传效果,可实现Ajax动态提...
1373 0
|
7月前
|
JavaScript
Jquery插件知识之Jquery.cookie实现页面传值
Jquery插件知识之Jquery.cookie实现页面传值
39 0
|
8月前
|
JavaScript
jQuery 插件自用列表
jQuery 插件自用列表
30 0