您的位置:首页 > Web前端 > JavaScript

javascript文件

2015-10-27 21:45 537 查看
uploadPreview.js

/*

*

*插件介绍:图片上传本地预览插件 兼容浏览器(IE 谷歌 火狐) 不支持safari 当然如果是使用这些内核的浏览器基本都兼容

*使用方法:

*界面构造(IMG标签外必须拥有DIV 而且必须给予DIV控件ID)

* <div id="imgdiv"><img id="imgShow" width="120" height="120" /></div>

* <input type="file" id="up_img" />

*调用代码:

* new uploadPreview({ UpBtn: "up_img", DivShow: "imgdiv", ImgShow: "imgShow" });

*参数说明:

*UpBtn:选择文件控件ID;

*DivShow:DIV控件ID;

*ImgShow:图片控件ID;

*Width:预览宽度;

*Height:预览高度;

*ImgType:支持文件类型 格式:["jpg","png"];

*callback:选择文件后回调方法;

*/

/*

*work:图片预览插件

*/

var uploadPreview = function(setting) {

    /*

 

    *work:this(当前对象)

    */

    var _self = this;

    /*

  

    *work:判断为null或者空值

    */

    _self.IsNull = function(value) {<
4000
br />
        if (typeof (value) == "function") { return false; }

        if (value == undefined || value == null || value == "" || value.length == 0) {

            return true;

        }

        return false;

    }

    /*

    *work:默认配置

    */

    _self.DefautlSetting = {

        UpBtn: "",

        DivShow: "",

        ImgShow: "",

        Width: 100,

        Height: 100,

        ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],

        ErrMsg: "选择文件错误,图片类型必须是(gif,jpeg,jpg,bmp,png)中的一种",

        callback: function() { }

    };

    /*

    *work:读取配置

    */

    _self.Setting = {

        UpBtn: _self.IsNull(setting.UpBtn) ? _self.DefautlSetting.UpBtn : setting.UpBtn,

        DivShow: _self.IsNull(setting.DivShow) ? _self.DefautlSetting.DivShow : setting.DivShow,

        ImgShow: _self.IsNull(setting.ImgShow) ? _self.DefautlSetting.ImgShow : setting.ImgShow,

        Width: _self.IsNull(setting.Width) ? _self.DefautlSetting.Width : setting.Width,

        Height: _self.IsNull(setting.Height) ? _self.DefautlSetting.Height : setting.Height,

        ImgType: _self.IsNull(setting.ImgType) ? _self.DefautlSetting.ImgType : setting.ImgType,

        ErrMsg: _self.IsNull(setting.ErrMsg) ? _self.DefautlSetting.ErrMsg : setting.ErrMsg,

        callback: _self.IsNull(setting.callback) ? _self.DefautlSetting.callback : setting.callback

    };

    /*

   

    *work:获取文本控件URL

    */

    _self.getObjectURL = function(file) {

        var url = null;

        if (window.createObjectURL != undefined) {

            url = window.createObjectURL(file);

        } else if (window.URL != undefined) {

            url = window.URL.createObjectURL(file);

        } else if (window.webkitURL != undefined) {

            url = window.webkitURL.createObjectURL(file);

        }

        return url;

    }

    /*

 

    *work:绑定事件

    */

    _self.Bind = function() {

    //判断当前的<input type="file">是否值改变了

        document.getElementById(_self.Setting.UpBtn).onchange = function() {

        //是否设置了值

            if (this.value) {

            //校验上传的文件是否是合法的后缀名

                if (!RegExp("\.(" + _self.Setting.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {

                    alert(_self.Setting.ErrMsg);

                    this.value = "";

                    return false;

                }

                //取出文件的地址

                if (navigator.userAgent.indexOf("MSIE") > -1) {

                    try {

                        document.getElementById(_self.Setting.ImgShow).src = _self.getObjectURL(this.files[0]);

                    } catch (e) {

                        var div = document.getElementById(_self.Setting.DivShow);

                        this.select();

                        top.parent.document.body.focus();

                        var src = document.selection.createRange().text;

                        document.selection.empty();

                        document.getElementById(_self.Setting.ImgShow).style.display = "none";

                        div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";

                        div.style.width = _self.Setting.Width + "px";

                        div.style.height = _self.Setting.Height + "px";

                        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;

                    }

                } else {

                    document.getElementById(_self.Setting.ImgShow).src = _self.getObjectURL(this.files[0]);

                }

                _self.Setting.callback();

            }

        }

    }

    /*

    

    *work:执行绑定事件

    */

    _self.Bind();
}

ajaxfileupload.js

    jQuery.extend({  

        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             

        },  
//创建一个表单  表单中有  file域  还有其他参数  都当成了

        createUploadForm: function(id, fileElementId, data)  

        {  

            //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>');   

            var oldElement = $('#' + fileElementId);  

            var newElement = $(oldElement).clone();  

            $(oldElement).attr('id', fileId);  

            $(oldElement).before(newElement);  

            $(oldElement).appendTo(form);  

              

            //增加文本参数的支持  

            if (data) {  

                for (var i in data) {  

                    $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);  

                }  

            }  

              

            //set attributes  

            $(form).css('position', 'absolute');  

            $(form).css('top', '-1200px');  

            $(form).css('left', '-1200px');  

            $(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, 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" );   // java 的 evoke

            }              

            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', up
a541
loadCallback);  

            }  

            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" )

            data = r.responseText;

            

            //alert("看看这个js里面的的data是什么:  " +data );

            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();  

                //alert($('param', data).each(function(){alert($(this).attr('value'));}));  

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

    })  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery