简单的jquery ajax上传插件ajaxfileupload

做web应用经常需要上传。

所以,ajax上传经常要用到。

分享个jquery的ajax上传组件ajaxfileupload。

用法很简单:

 代码如下 复制代码

<!DOCTYPE HTML>
<html lang="en">
<html>
<head>
    <title>上传demo</title>
    <meta charset="utf-8">
    <script src="/js/jquery-1.8.3.min.js"></script>
    <script src="/js/ajaxfileupload.js"></script>
</head>
<body>
<input type="file" id="fileInput" name="good" />&nbsp;<a href="javascript:upload()">上传</a>
<script type="text/javascript">
function upload(){
    $.ajaxFileUpload ({
        ckeditor/" target="_blank">fckeditor/editor/'/upload.html'">url:'/upload.html',
        fileElementId:'fileInput',
        success: function (data, status)
        {
            alert("success");
            alert(data);
        },
        error: function (data, status, e)
        {
            alert("error");
            alert(e);
        }
    })
}
</script>
</body>
</html>

/upload.html其实就是一般的上传路径而已。

当然,有时用新的jquery的时候,会报handleError异常。

没关系,是新jquery去掉了这个方法而已,我们在组件后面加一个就可以了。

 代码如下 复制代码

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

就这么简单。

修改后的组件代码哪下

 代码如下 复制代码

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)
            {
                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 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?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;
        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;
    },

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

时间: 2024-08-02 17:25:01

简单的jquery ajax上传插件ajaxfileupload的相关文章

Jquery uploadify上传插件使用详解_jquery

Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示.不过官方提供的实例时php版本的,本文将详细介绍Uploadify在Aspnet中的使用,您也可以点击下面的链接进行演示或下载. 首先按下面的步骤来实现一个简单的上传功能. 1 创建Web项目,命名为JQueryUploadDemo,从官网上下载最新的版本解压后添加到项目中. 2 在项目中添加UploadHandler.ashx文件用来处理文件的上传. 3 在项目中添加UploadFile文件夹,用来存放上传的文件.

jQuery Uploadify 上传插件出现Http Error 302 错误的解决办法_jquery

前段时间介绍过jquery uploadify上传插件的使用方法,我在使用中遇到过Http Error 302错误问题,应该会有很多人在使用中遇到过,在此记录下来: 首先http 302是请求被重定向的意思,这就很容易理解了,如果你的uploadify处理上传脚本有session验证,就会出现此错误,因为flash在执行post请求的时候没有包含cookie信息,而服务器的session会根据客户端的cookie来得到SESSIONID.没有提交cookie自然就不能获取到session,然后u

jQuery Ajax 上传文件处理方式介绍(推荐)_jquery

AJAX 是一种与服务器交换数据的技术,可以在补充在整个页面的情况下更新网页的一部分. 下面的表格列出了所有的 jQuery AJAX 方法: jQuery Ajax在web应用开发中很常用,它主要包括有ajax,get,post,load,getscript等等这几种常用无刷新操作方法,接下来通过本文给大家介绍jquery ajax 上传文件处理方式. FormData对象 XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过J

分享20多个很棒的jQuery 文件上传插件或教程_jquery

1. Plupload Plupload 是一个Web浏览器上的界面友好的文件上传模块,可显示上传进度.图像自动缩略和上传分块.可同时上传多个文件. 2. The KillersAjax Upload 该插件使用 XHR 用于上传多个文件,支持上传进度显示,但不支持 IE 3. SWFUpload jQuery Plugin 4. AjaxFileUpload 5. Uploadify Uploadify简单说来,是基于Jquery的一款文件上传插件.它的功能特色总结如下: 支持单文件或多文件上

20+ 个很棒的 jQuery 文件上传插件或教程(此文值得“推荐”和“收藏”)

文件上传是网站很常见的功能之一,通过使用 jQuery 可以让上传过程更加人性化,更好的用户体验.本文介绍20个jQuery的文件上传插件,其中有一些是教程. 1. Plupload Plupload 是一个Web浏览器上的界面友好的文件上传模块,可显示上传进度.图像自动缩略和上传分块.可同时上传多个文件. 2. The KillersAjax Upload 该插件使用 XHR 用于上传多个文件,支持上传进度显示,但不支持 IE 3. SWFUpload jQuery Plugin 4. Aja

20+ 个很棒的 jQuery 文件上传插件或教程

文件上传是网站很常见的功能之一,通过使用 jQuery 可以让上传过程更加人性化,更好的用户体验.本文介绍20个jQuery的文件上传插件,其中有一些是教程. 1. Plupload Plupload 是一个Web浏览器上的界面友好的文件上传模块,可显示上传进度.图像自动缩略和上传分块.可同时上传多个文件. 2. The KillersAjax Upload 该插件使用 XHR 用于上传多个文件,支持上传进度显示,但不支持 IE 3. SWFUpload jQuery Plugin 4. Aja

Jquery文件上传插件:Jquery html5 uploader

文章简介:Jquery html5 uploader插件使用笔记. Jquery html5 uploader 是Jquery的一个文件上传插件,支持拖拽上传,但要求浏览器支持html5 1.下载插件 http://www.igloolab.com/jquery-html5-uploader/ 具体演示也可在这里看到. 2.引入不要文件 <script type="text/javascript" src="http://ajax.googleapis.com/ajax

基于jquery的上传插件Uploadify 3.1.1在MVC3中的使用

   Uploadify是JQuery的一个文件上传插件,实现的效果非常不错,目前已经更新到Version3.1.1,官方提供的实例是php版本的,本文将介绍Uploadify在MVC3中的使用,您可以点击以下链接,去官网查看文档,下载Uploadify插件. 下载Uploadify插件 查看文档  下载Uploadify插件,然后按照以下步骤,在MVC3中应用Uploadify3.1.1插件的上传功能吧. 1.创建MVC3工程,本例命名为UploadifyTest 2.把解压后的Uploadi

jquery文件上传插件:upload无刷新AJAX进度多文件批量上传示例

1.插件说明 在支持FormData的浏览器完全使用AJAX(即XMLHttpRequest)和input的files属性共同完成上传文件,否则就模拟表单提交来上传文件.支持写的文章和脚本现在看起来都比较稚嫩,现在重新整理.约束,更好的API和便捷使用方法. 插件名称:jquery-upload. 2.插件使用 // 1.判断浏览器支持特征 // 是否支持HTML5的input的files对象,用于同时选择上传多张图片 $.support.inputFiles; // 是否支持HTML5的For