兼容低版本IE上传预览插件

ajaxfileupload.js 部分:

~~~~~~~~~~~~~~~~~~~~~~~~~~

jQuery.extend( {
handleError : function(s, xhr, status, e) {
if (s.error)
s.error(xhr, status, e);
else if (xhr.responseText)
console.log(xhr.responseText);
}
});
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(jQuery.browser.version=="9.0" || jQuery.browser.version=="10.0"){  
//         var io = document.createElement('iframe');  
//         io.id = frameId;  
//         io.name = frameId;  
//     }else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0"){  
//         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;  
//         }  
//     }  
// }  



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


//做一些修改
// var t = '';
//    if(typeof(fileElementId) == 'string'){
//    /*
//    * 将传过来的值 如:"file1,file2,file3" 转换为:['file1','file2','file3']  
//    */
//    var s = fileElementId.split(",");
//    for(var i in s){
//    t = t +  "'"+s[i]+"'"+",";
//    }
//        t = "["+t+"]";  
//        t = t.replace(",]", "]")
//    }  
//    fileElementId= eval('('+ t +')'); //将string类型转换为Object类型
//    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);  
//    }  
if(typeof(fileElementId) == 'string'){
    fileElementId = [fileElementId];
}
for(var i in fileElementId){
    var oldElement = jQuery("input[id="+fileElementId[i]+"]");
    oldElement.each(function() {
        var newElement = jQuery($(this)).clone();
        jQuery(oldElement).attr('id', fileId);
        jQuery(oldElement).before(newElement);
        jQuery(oldElement).appendTo(form);
    });
}
    //end
    
// 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);
eval("data = \" "+data+" \" ");
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();


return data;
}
})

``~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`

视图uploadPreviews.js

jQuery.fn.extend({

    uploadPreview: function (opts) {
//  var list=["ImgPr,"]
        var _self = this,
            _this = $(this);
        opts = jQuery.extend({
            Img: "ImgPr",
            Width: 100,
            Height: 100,
            ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
            Callback: function () {}
        }, opts || {});
        _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
        };
        _this.change(function () {


            if (this.value) {
                var isIE = /msie/i.test(navigator.userAgent) && !window.opera; 
                    var fileSize = 0; 
                    var filepath = this.value; 
                    var filemaxsize = 1024*1;//1M 
                    var size;
                    var bum=0;
                      //ie8浏览器下的判断
                    if (isIE && !target.files) { 
                        
                    } else { 
                        size = this.files[0].size / 1024;
                        if(size>filemaxsize){ 
                            bum=1; 
                        } 
                    } 
                if (!RegExp("\.(" + opts.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase()) ||bum==1) {
        
                    if( bum!=1){
                        alert("选择文件错误,图片类型必须是" + opts.ImgType.join(",") + "中的一种");
                    }else{
                         alert("附件大小不能大于"+filemaxsize/1024+"M!");
                    }


                    this.value = "";
                   $(this).siblings(".ii").show();
                   $(this).siblings("img").attr("src"," ");
                   $(this).parent(".maxL").css("filter"," ");
                   $(this).siblings(".font_style").find("img").attr("src"," ");
                   $(this).siblings(".font_style").css("filter"," ");
                    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
                    var isOpera = userAgent.indexOf("Opera") > -1;
                      //IE8+
                    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
                        var pinId=$(this).attr("id");
                        if($(this).siblings("font_style").find("img").attr("id")){
                            var imgId=$(this).siblings("font_style").find("img").attr("id");
                             $("#"+pinId).after($("#"+pinId).clone().val("")); 
                            $("#"+pinId).remove();
                            $("#"+pinId).uploadPreview({ Img: imgId, Width: 60, Height: 60 });
                        }else if($(this).siblings("img").attr("id")){
                            var imgId=$(this).siblings("img").attr("id");
                          $("#"+pinId).after($("#"+pinId).clone().val("")); 
                         $("#"+pinId).remove();
                         $("#"+pinId).uploadPreview({ Img: imgId, Width: 120, Height: 120 });
                        }
                        
                     }
                    return false;
                }
                if ($.browser.msie) {
     
                    try {
                        $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
                    } catch (e) {
                        var src = "";
                        var obj = $("#" + opts.Img);
                        var div = obj.parent("div")[0];
                        _self.select();
                        if (top != self) {
                            window.parent.document.body.focus()
                        } else {
                            _self.blur()
                        }
                        src = document.selection.createRange().text;
                        document.selection.empty();
                        
                       
                        obj.attr("src",src);
                        obj.hide();
                        obj.parent("div").css({
                            'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
                            'width': opts.Width + 'px',
                            'height': opts.Height + 'px'
                        });
                        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
                    }
                } else {
                    $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
                 
                }
                opts.Callback()
            }
        })
    }

});

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

html 部分:

<div>
                               <form action="" enctype="multipart/form-data" id="main">
                                <div id="maxFile">
                                    <div id="addFile" >
                                        <div class="maxL"  >
                                            <img id="ImgPr1" width="120" height="120" class='img'  />
                                            <span class="ii"></span>
                                            <input type="file" id="file1" name="file" οnchange="changes(this)"  />
                                        </div>
                                    </div> 
                                </div>
                                    <a id="add" href="javascript:void(0);"  οnclick="addFile()">添加图片</a>
                                </br>
                                <span style='clear: both;' ></span>
                                <div class="ButStyles">
                                    <input type="button" class="submitBut" οnclick="uploadFile()" value="确定">
                                </div>
                                
                            </form>
                          

                        </div>


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

js部分:

  function uploadFiles(t) {
        var fileIds = new Array();
        var tagElements = $(t).parents(".maxLs").find("input"); 


            if(tagElements.val()==''||tagElements.val()==undefined){
                return ;
            }
           
        for (var j = 0; j < tagElements.length; j++) {
            element = tagElements[j];
            if ("file" == element.type) {
                fileIds.push(element.id);
            }
        }
        var $this= $(t);        
        $.ajaxFileUpload( {
            url : "{:U('Gengdan/end_pro_barcode_upload')}",     
            secureuri : false,          
            fileElementId : fileIds,       
             dataType:"content",     
            success : function(data, status) {
                
            },
            error:function(data,status){
         
            }
        })
    }

~~~~~~~~~~~~~~~~~~~~~~~~~~

  $(function () {
            $("#file1").uploadPreview({ Img: "ImgPr1", Width: 120, Height: 120 });      
        });
    //添加附件 
    function addFile(){
        var fileLength =$("#maxFile>div").length+1;


        var inputFile = "<div id='addFile"+fileLength+"'style='position: relative' ><div class='maxL'  > <img id='ImgPr"+fileLength+"' class='img'  width='120' height='120'  /><span class='ii'></span><input type='file' id='file"+fileLength+"' name='file"+fileLength+"' οnchange='changes(this)' />"
                    +"<span style='clear: both;' ></span><a href='javascript:void(0);'  class='kk' οnclick='delFile("+fileLength+");'>X</a></div ></div>";
        
        $("#main #maxFile").append(inputFile);
        $("#main #file"+fileLength+"").uploadPreview({ Img: "ImgPr"+fileLength+"", Width: 120, Height: 120 });
        
    }
    //删除附件
    function delFile(id){
        $("#addFile"+id).remove();
    }


    function uploadFile(contextPath) {


       var txtbeizu= $('.txtbeizu').val();
        if( $.trim(txtbeizu)==''){
            $.jtool.alert('请填写留言!', false);
            return false; 
        }




        var fileIds = new Array();
   
        var tagElements = $("#maxFile input[type=file]");
        var inplength=0;
        tagElements.each(function(){
            
            if($(this).val()){
                inplength=1;
            }
        })


        if(inplength==1){


        
        for (var j = 0; j < tagElements.length; j++) {
            element = tagElements[j];
            if ("file" == element.type) {
                fileIds.push(element.id);
            }
        }


        $.ajaxFileUpload( {
            url : '__APP__/Gengdan/save_img',     
            secureuri : false,       
            fileElementId : fileIds,         
            dataType:"content",     
            success : function(data, status) {
                var datar =data.split(",");
                for(var i = 0;i<datar.length; i++){
                     img_datas.push(datar[i]);
                }
               
                console.log(img_datas)
               if(img_datas!=undefined || img_datas!='' || img_datas!=[] ){
                    liuyan();
               }
            },
            error:function(data,status){
              
            }
        })
      }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值