jquery插件---模拟from表单上传文件,实现异步提交

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, fileElementId2) {
        //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);

        if (fileElementId2) {
            var oldElement2 = jQuery(‘#‘ + fileElementId2);
            var newElement2 = jQuery(oldElement2).clone();
            jQuery(oldElement2).attr(‘id‘, fileId);
            jQuery(oldElement2).before(newElement);
            jQuery(oldElement2).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;
        if (s.morethan) {
            form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == ‘undefined‘ ? false : s.data), s.fileElementId2);
        }
        else {
            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;
    }
})

  使用:

            $.ajaxFileUpload({
                url: ‘‘,
                secureuri: false,
                data: {
                    LoginName: _LoginName,//用户名
                    MPSW: _MPSW,//密码
                    RePSW: _RePSW,//确认密码
                    MTel: _MTel,//手机
                    MName: _MName,//真实姓名
                    VCode: _VCode,//验证码
                    CName: _CName,//公司名称
                    LName: _LName,//法人
                    LPID: _LPID,//身份证号
                    CAddress: _CAddress,//公司地址
                },
                fileElementId: ‘file1‘,//上传file控件
                fileElementId2: ‘file2‘,//上传file控件
                morethan: true,//支持两张图片上传
                dataType: ‘json‘,//返回值类型
                success: function (data, status) {
                    alert(‘处理代码!‘);
                },
                error: function (data, status, e) {
                    alert(‘发生错误‘);
                }
            });

  

时间: 2025-01-02 04:08:00

jquery插件---模拟from表单上传文件,实现异步提交的相关文章

C# 模拟Form表单上传文件方法

public static string UploadFile(string url, HttpPostedFileBase file,string FieldName) { Stream fs = file.InputStream; if (!fs.CanRead) { return ""; } byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); fs.Close(); string bou

PHP CURL 模拟form表单上传遇到的小坑

1:引用的时候 $parans ['img']=new \CURLFile($param); 传入的文件 在PHP版本5.5以上记得new CURLFile 不然会上传不成功 /** * http post请求--CURL模拟表单上传文件 * @param $url string 请求地址 * @param $params array 请求参数 * @param $header array 请求头 * @return mixed */ protected function _httpPostIm

android form表单上传文件

原文地址:http://menuz.iteye.com/blog/1282097 Android程序使用http上传文件 有时,在网络编程过程中需要向服务器上传文件.Multipart/form-data是上传文件的一种方式. Multipart/form-data其实就是浏览器用表单上传文件的方式.最常见的情境是:在写邮件时,向邮件后添加附件,附件通常使用表单添加,也就是用multipart/form-data格式上传到服务器.  Html代码   <form action="/Test

django 基于form表单上传文件和基于ajax上传文件

一.基于form表单上传文件 1.html里是有一个input type="file" 和 'submit'的标签 2.vies.py def fileupload(request): if request.method == 'POST': print(request.POST) print(request.FILES) # from django.core.files.uploadedfile import InMemoryUploadedFile print(type(reque

使用form表单上传文件

在使用form表单上传文件时候,input[type='file']是必然会用的,其中有一些小坑需要避免. 1.form的 enctype="multipart/form-data" 已经是个老生常谈的问题了,相信都能注意到,就不多说了. 2.上传下载的请求是不能用ajax提交返回json的. 3.当使用input[type='file'] 的onChange事件来触发文件上传的时候要注意当上传成功时清空input的时候,不能简单的使用$("input").val(

关于form表单上传文件的问题

最近在学习php,刚好学到利用表单上传文件这一知识.在学习的过程中,出现了这样几个问题,我是小白,还请高手指点. 大家都知道在上传文件时,我们要设置表单的MIME编码.默认情况,enctype的编码格:application/x-www-form-urlencoded,不能用于文件上传, 只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.但是我在接下来的操作中,遇到了这样的问题. <?php   if (isset($_POST['submit']) &

form表单上传文件

注意form表单上传文件的时候,要加上   enctype这个属性 原文地址:https://www.cnblogs.com/xiaoxiaoyao/p/8541923.html

ajax上传文件 基于jquery form表单上传文件

<script src="/static/js/jquery.js"></script><script> $("#reg-btn").click(function () { // 1. 取到用户填写的数据 var form_data_obj = new FormData(); form_data_obj.append('username',$('#id_username').val()); form_data_obj.append

php5.6 curl 模拟表单上传文件

php5.5之后php官方推荐使用CURLFile类来模拟代替之前的@+全文件路径方式上传文件 if(class_exists('\CURLFile')) { //可以使用 $filedata = [ 'fieldname' => new \CURLFile ( realpath ( $filepath ), 'image/jpeg' ) ]; } else { //不可使用CURLFile,及旧模式 $filedata = [ 'fieldname' => '@'.realpath($fil