使用ajaxfileupload插件进行Ajax Post 异步提交多个文件

前台代码:

    <div>
        <div>
            <img src="images/pro_upload.png"  onclick="javascript:document.getElementById(‘pic1‘).click();" />
            <input type="file" hidden="hidden" id="pic1" name="pic1"  />
        </div>
        <div>
            <img src="images/pro_upload.png"  onclick="javascript:document.getElementById(‘pic2‘).click();" />
            <input type="file" hidden="hidden" id="pic2" name="pic2"  />
        </div>
        <span id="btn">提交</span>
    </div>

	<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
    <script src="../JS/ajaxfileupload.js"></script>

    <script>
        document.getElementById("btn").onclick = function () {
            $.ajaxFileUpload({
                url: "FileTestHanlder.ashx?param=testParam",//可以携带多个其他参数
                secureuri: false,
                fileElementId: ["pic1","pic2"], //对应的文件表单域name属性
                dataType: "TEXT",
                success: function (data, status) {
                    alert(data);
                }
            });
        }
    </script>

  

后台代码:

public class FileTestHanlder : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.Write(context.Request.Files["pic1"].ContentLength + context.Request.Files["pic2"].ContentLength + context.Request["param"]);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

  

ajaxfileupload.js插件代码(有改动):

jQuery.extend({
    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] );
        }
    } ,

    createUploadIframe: function(id, uri)
    {
        //create frame
        var frameId = ‘jUploadFrame‘ + id;

        if(window.ActiveXObject) {
            var io = document.createElement(‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" />‘);
            if(typeof uri== ‘boolean‘){
                io.src = ‘javascript:false‘;
            }
            else if(typeof uri== ‘string‘){
                io.src = uri;
            }
        }
        else {
            var io = document.createElement(‘iframe‘);
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = ‘absolute‘;
        io.style.top = ‘-1000px‘;
        io.style.left = ‘-1000px‘;

        document.body.appendChild(io);

        return io
    },
    createUploadForm: function(id, fileElementId)
    {
        //create form
        var formId = ‘jUploadForm‘ + id;
        var fileId = ‘jUploadFile‘ + id;
        var form = $(‘<form  action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data"></form>‘);
        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);
        }
        //set attributes
        $(form).css(‘position‘, ‘absolute‘);
        $(form).css(‘top‘, ‘-1200px‘);
        $(form).css(‘left‘, ‘-1200px‘);
        $(form).appendTo(‘body‘);
        return form;
    },
    addOtherRequestsToForm: function(form,data)
    {
        // add extra parameter
        var originalElement = $(‘<input type="hidden" name="" value="">‘);
        for (var key in data) {
            name = key;
            value = data[key];
            var cloneElement = originalElement.clone();
            cloneElement.attr({‘name‘:name,‘value‘:value});
            $(cloneElement).appendTo(form);
        }
        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);
        if ( s.data ) form = jQuery.addOtherRequestsToForm(form,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
                    {
                        $(io).remove();
                        $(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 io = $(‘#‘ + frameId);
            var form = $(‘#‘ + formId);
            $(form).attr(‘action‘, s.url);
            $(form).attr(‘method‘, ‘POST‘);
            $(form).attr(‘target‘, frameId);
            if(form.encoding)
            {
                form.encoding = ‘multipart/form-data‘;
            }
            else
            {
                form.enctype = ‘multipart/form-data‘;
            }
            $(form).submit();

        } catch(e)
        {
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent(‘onload‘, uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener(‘load‘, uploadCallback, false);
        }
        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" )
        {
            // If you add mimetype in your response,
            // you have to delete the ‘<pre></pre>‘ tag.
            // The pre tag in Chrome has attribute, so have to use regex to remove
            var data = r.responseText;
            var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
            var am = rx.exec(data);
            //this is the desired data extracted
            var data = (am) ? am[1] : "";    //the only submatch or empty
            eval( "data = " + data );
        }
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
        //alert($(‘param‘, data).each(function(){alert($(this).attr(‘value‘));}));
        return data;
    }
})

  

时间: 2024-10-10 02:42:05

使用ajaxfileupload插件进行Ajax Post 异步提交多个文件的相关文章

.net mvc Ajax.BeginForm 异步提交表单

Ajax.BeginForm异步表单用validform验证插件...... 之前找了一个jquery的验证插件validform,对此插件很满意,但是这个插件对<input type="button">按钮不感冒(检测不到这个按钮的onclick事件),只检测<input type="submit">的提交事件. 于是乎想到mvc 有一个异步表单Ajax.BeginForm,经测试可用.记录下来以便查阅 <script src=&qu

原生AJAX如何异步提交数据?

AJAX概述 AJAX:Asynchronous Javascript And XML,异步的JS和XML.2001,Google为了改进搜索的用户体验,提出了GoogleSugguest效果,正式提出了AJAX的概念. 目标:在无刷新无提交的情况下,实现页面内容的局部更新--数据来自于服务器. 常见应用:实时数据获取(如股票走势图).搜索建议.聊天室.SPA AJAX应用依赖于浏览器底层提供的核心对象: XMLHttpRequest:用于向Web服务器发起异步请求,并接收响应消息. 使用XHR

ajax测试异步提交

今天测试了$.ajax()方法: $("a").click(function(){        $.ajax({           url:"MyJsp.jsp",           type:"GET",           success:function(msg){           $("body").append(msg);         } 参数url是目标地址源,type:是请求提交类型,success

TP 框架 ajax[利用异步提交表单]

1 //[] 2 3 $(function () { 4 $("#send-btn" ).click(function (){ 5 //接受表单的值 6 var username=$('input[name=username]').val(); 7 var content=$('textarea[name=content]').val(); 8 if(username==''){ 9 alert('用户名不能为空!'); 10 username.focus(); 11 return ;

ajax.BeginForm异步提交表单并更新数据

using (Ajax.BeginForm("GetBasicInformation", "Employee", //new AjaxOptions { UpdateTargetId = "basicInfo", //设置HTML元素的ID,从服务器接收的内容将被插入到该元素中LoadingElementId="loading",//指定HTML元素的ID,这是执行ajax请求其间要显示的HTML元素 LoadingEleme

使用jQuery.form插件,实现完美的表单异步提交

示例下载:使用jQuery.form插件,实现完美的表单异步提交.rar 抓住6月份的尾巴,今天的主题是 今天我想介绍的是一款jQuery的插件:Jquery.form.js 官网. 通过该插件,我们可以非常简单的实现表单的异步提交,并实现文件上传.进度条显示等等. 现在我们从一个ASP.NET同步表单提交开始,然后再将其转化为异步的表单提交.我写了3种表单提交示例,并简单分析了各种方式的利弊. 当然主题还是使用jQuery表单插件轻松实现表单异步提交以及分析下该插件的源码. ASP.NET服务

jQuery.form.js jQuery ajax异步提交form

jQuery.form.js是一个form插件,支持ajax表单提交和ajax文件上传. 官网下载地址:http://plugins.jquery.com/form/ API ajaxForm 增加所有需要的事件监听器,为ajax提交表单做准备.ajaxForm并不能提交表单.在document的ready函数中,使用ajaxForm来为ajax提交表单进行准备. 接受0个或1个参数.参数可以是一个回调函数,也可以是一个Options对象. $("#formid").ajaxForm(

Ajax表单提交

jQuery Form插件是一个优秀的Ajax表单插件,可以非常容易地.无侵入地升级HTML表单以支持Ajax.jQuery Form有两个核心方法 -- ajaxForm() 和 ajaxSubmit(), 它们集合了从控制表单元素到决定如何管理提交进程的功能.另外,插件还包括其他的一些方法: formToArray().formSerialize().fieldSerialize().fieldValue().clearForm().clearFields() 和 resetForm()等.

使用ajax异步提交表单

虽然这篇文章的标题是提交表单,但是主要的难点在于使用ajax提交文本域的内容, 在工作中的经常会需要ajax跨域的问题,通常的需求使用jsonp就可以得到解决,但是当前项目中有一个图片服务器,客户端需要直接上传图片到图片服务器中,这就产生了一个跨域post提交文件的问题,很显然jquery本身jsonp只支持get方式的异步提交肯定是不行 其中也尝试过使用ifrmae的方法来提交数据,在网上有,但是效果不理想,并且也很复杂的样子,最后选择出了jquery.from.js 这个插件,可以实现异步的