Ajax上传文件

发布于 2018-08-18  11 次阅读


可采用ajaxfileupload.js来上传文件

$.ajaxFileUpload({
                type: "POST",
                url: "convert",
                secureuri: false,
                fileElementId: "file-audio",
                dataType: 'json',
                success: function (data, status) {
                    //上传成功
                },
                error: function (data, status, e) {
                   //上传失败
                }
            })

参数说明

  • url 对应的处理程序的地址  
  • fileElementId 文件输入框的id
  • dataType 返回数据类型,可以为xml,script,json,html,留空自动判断
  • success 成功后的处理函数,参数data就是服务器返回的数据
  • error 失败后的处理函数
  • data 自定义参数

样例

摘自小学期项目-说话人转换系统,其中还用到了bootstrap-toastr和boostrap-fileinput

$(function () {
        toastr.options = {
            "closeButton": false,
            "debug": false,
            "positionClass": "toast-top-center",
            "onclick": null,
            "showDuration": "1000",
            "hideDuration": "1000",
            "timeOut": "3000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        };

        $('#file-audio').fileinput({
            language: 'zh',
            allowedFileTypes: ["audio"],
            showUpload: false,
            showPreview: true,
            uploadAsync: false
        });

        $("#btn-submit").click(function () {
            $("#myModal").modal('show');
            $.ajaxFileUpload({
                type: "POST",
                url: "convert",
                secureuri: false,
                fileElementId: "file-audio",
                dataType: 'json',
                success: function (data, status) {
                    $("#myModal").modal('hide');
                    $("#file-wrapper").html('<input type="file" id="file-audio" name="file"/>');
                    $('#file-audio').fileinput({
                        language: 'zh',
                        allowedFileTypes: ["audio"],
                        showUpload: false,
                        showPreview: true,
                        uploadAsync: false
                    });
                    if (data.code === 0) {
                        console.log(data);
                        $("#result").show();
                        $("#source").html("<audio src='uploads/" + data.source + "' controls='controls'></audio>");
                        $("#target").html("<audio src='uploads/" + data.target + "' controls='controls'></audio>")
                        toastr["success"]("转换成功", "转换成功")
                    } else {
                        toastr["error"](data.message, "转换失败");
                    }
                },
                error: function (data, status, e) {
                    $("#myModal").modal('hide');
                    $("#file-wrapper").html('<input type="file" id="file-audio" name="file"/>');
                    $('#file-audio').fileinput({
                        language: 'zh',
                        allowedFileTypes: ["audio"],
                        showUpload: false,
                        showPreview: true,
                        uploadAsync: false
                    });
                    toastr["error"](e, "网络请求失败");
                }
            })
        });

    })

附ajaxfileupload.js

该文件对应的jq版本较低,所以进行过改动

jQuery.extend({createUploadIframe:function(d,b){var a="jUploadFrame"+d;var c='<iframe id="'+a+'" name="'+a+'" style="position:absolute; top:-9999px; left:-9999px"';if(window.ActiveXObject){if(typeof b=="boolean"){c+=' src="'+"javascript:false"+'"'}else{if(typeof b=="string"){c+=' src="'+b+'"'}}}c+=" />";jQuery(c).appendTo(document.body);return jQuery("#"+a).get(0)},createUploadForm:function(a,j,d){var h="jUploadForm"+a;var c="jUploadFile"+a;var b=jQuery('<form  action="" method="POST" name="'+h+'" id="'+h+'" enctype="multipart/form-data"></form>');if(d){for(var e in d){if(d[e].name!=null&&d[e].value!=null){jQuery('<input type="hidden" name="'+d[e].name+'" value="'+d[e].value+'" />').appendTo(b)}else{jQuery('<input type="hidden" name="'+e+'" value="'+d[e]+'" />').appendTo(b)}}}var f=jQuery("#"+j);var g=jQuery(f).clone();jQuery(f).attr("id",c);jQuery(f).before(g);jQuery(f).appendTo(b);jQuery(b).css("position","absolute");jQuery(b).css("top","-1200px");jQuery(b).css("left","-1200px");jQuery(b).appendTo("body");return b},ajaxFileUpload:function(k){k=jQuery.extend({},jQuery.ajaxSettings,k);var a=new Date().getTime();var b=jQuery.createUploadForm(a,k.fileElementId,(typeof(k.data)=="undefined"?false:k.data));var i=jQuery.createUploadIframe(a,k.secureuri);var h="jUploadFrame"+a;var j="jUploadForm"+a;if(k.global&&!jQuery.active++){jQuery.event.trigger("ajaxStart")}var c=false;var f={};if(k.global){jQuery.event.trigger("ajaxSend",[f,k])}var d=function(l){var p=document.getElementById(h);try{if(p.contentWindow){f.responseText=p.contentWindow.document.body?p.contentWindow.document.body.innerHTML:null;f.responseXML=p.contentWindow.document.XMLDocument?p.contentWindow.document.XMLDocument:p.contentWindow.document}else{if(p.contentDocument){f.responseText=p.contentDocument.document.body?p.contentDocument.document.body.innerHTML:null;f.responseXML=p.contentDocument.document.XMLDocument?p.contentDocument.document.XMLDocument:p.contentDocument.document}}}catch(o){jQuery.handleError(k,f,null,o)}if(f||l=="timeout"){c=true;var m;try{m=l!="timeout"?"success":"error";if(m!="error"){var n=jQuery.uploadHttpData(f,k.dataType);if(k.success){k.success(n,m)}if(k.global){jQuery.event.trigger("ajaxSuccess",[f,k])}}else{jQuery.handleError(k,f,m)}}catch(o){m="error";jQuery.handleError(k,f,m,o)}if(k.global){jQuery.event.trigger("ajaxComplete",[f,k])}if(k.global&&!--jQuery.active){jQuery.event.trigger("ajaxStop")}if(k.complete){k.complete(f,m)}jQuery(p).unbind();setTimeout(function(){try{jQuery(p).remove();jQuery(b).remove()}catch(q){jQuery.handleError(k,f,null,q)}},100);f=null}};if(k.timeout>0){setTimeout(function(){if(!c){d("timeout")}},k.timeout)}try{var b=jQuery("#"+j);jQuery(b).attr("action",k.url);jQuery(b).attr("method","POST");jQuery(b).attr("target",h);if(b.encoding){jQuery(b).attr("encoding","multipart/form-data")}else{jQuery(b).attr("enctype","multipart/form-data")}jQuery(b).submit()}catch(g){jQuery.handleError(k,f,null,g)}jQuery("#"+h).load(d);return{abort:function(){}}},uploadHttpData:function(r,type){var data=!type;if(!type){data=r.responseText}if(type=="xml"){data=r.responseXML}if(type=="script"){jQuery.globalEval(data)}if(type=="json"){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)}if(type=="html"){jQuery("<div>").html(data).evalScripts()}return data},handleError:function(b,d,a,c){if(b.error){b.error.call(b.context||b,d,a,c)}if(b.global){(b.context?jQuery(b.context):jQuery.event).trigger("ajaxError",[d,b,c])}}});