• Huplaodfiy---图片文件上传插件修改


    说明:

       本文是将Hupladify进行修改,实现功能:

         1.批量上传

         2.预览

         3.多选去重

     问题:

       不兼容IE10以下浏览器

    实例:

    html:

    <link rel="stylesheet" type="text/css" href="Huploadify.css"/>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="jquery.Huploadify.js"></script>
     1 <body>
     2 
     3 <div class="upload uploadStyle uploadify" ></div>
     4 
     5 <div class="preview_model">
     6    <div class="preview_model_container">
     7      <img id="preview_img" src="" />
     8    </div>
     9 </div>
    10 
    11 
    12 </body>

    js:

     1 <script type="text/javascript">
     2 $(function(){
     3     $(".preview_model").click(function(){
     4         $(this).hide();
     5     });
     6     $('.uploadify').Huploadify({
     7         auto:false,
     8         preview:true,
     9         fileTypeExts:'*.jpg;*.png;*.bmp;*.docx;*.xsl;*.doc;*.rar;',
    10         multi:true,
    11         formData:{key:123456,key2:'vvvv'},
    12         fileSizeLimit:9999,
    13         showUploadedPercent:true,//是否实时显示上传的百分比,如20%
    14         showUploadedSize:true,
    15         fileObjName:'attachmentFile',
    16         removeTimeout:1000,
    17         uploader:'http://localhost:8181/front/customer/distributor/uploadAttachment.action',
    18         onUploadStart:function(){
    19             //alert('开始上传');
    20             },
    21             onUploadSuccess:function(){
    22                 alert("上传成功");
    23             },
    24             onUploadError:function(){
    25                 alert("上传失败");
    26                
    27             },
    28         onInit:function(){
    29             
    30             //alert('初始化');
    31             },
    32         onUploadComplete:function(){
    33             //alert("上传完成");
    34             $(".uploadify-all-button").off("click");
    35             },
    36         onCancel:function(file){
    37             
    38             
    39          }
    40         });
    41     
    42      
    43     });
    44     
    45     
    46 </script>

    Huploadify.js

    (function($){
    $.fn.Huploadify = function(opts){
        
        var itemTemp = '';
         itemTemp += '<div id="${fileID}" class="uploadify-queue-item">'
         itemTemp +=     '<div class="uploadify-content">'
         itemTemp +=       '<span class="up_filename">${fileName}</span>'
         itemTemp +=     '</div>'
         itemTemp +=     '<div class="uploadify-bar">'
         itemTemp +=     '<div class="uploadify-progress-container">'     
         itemTemp +=        '<div class="uploadify-progress"><div class="uploadify-progress-bar"></div></div>'
         itemTemp +=     '</div>'
         itemTemp +=     '<span class="uploadbtn"></span>'
         itemTemp +=     '<span class="delfilebtn"></span>'
             
         itemTemp +=     '</div>'
         
         itemTemp += '</div>';
         
         var fileArr = [];
         
         
         var defaults = {
            fileTypeExts:'',//允许上传的文件类型,格式'*.jpg;*.doc'
            uploader:'',//文件提交的地址
            auto:false,//是否开启自动上传
            preview:false,//是否预览
            method:'post',//发送请求的方式,get或post
            multi:true,//是否允许选择多个文件
            formData:null,//发送给服务端的参数,格式:{key1:value1,key2:value2}
            fileObjName:'file',//在后端接受文件的参数名称,如PHP中的$_FILES['file']
            fileSizeLimit:1024*10,//允许上传的文件大小,单位KB
            showUploadedPercent:true,//是否实时显示上传的百分比,如20%
            showUploadedSize:false,//是否实时显示已上传的文件大小,如1M/2M
            buttonText:'选择文件',//上传按钮上的文字
            uploadbtnText:'上传',
            removeTimeout: 1000,//上传完成后进度条的消失时间
            itemTemplate:itemTemp,//上传队列显示的模板
            onUploadStart:null,//上传开始时的动作
            onUploadSuccess:null,//上传成功的动作
            onUploadComplete:null,//上传完成的动作
            onUploadError:null, //上传失败的动作
            onInit:null,//初始化时的动作
            onCancel:null//删除掉某个文件后的回调函数,可传入参数file
        }
            
        var option = $.extend(defaults,opts);
        
        //将文件的单位由bytes转换为KB或MB,若第二个参数指定为true,则永远转换为KB
        var formatFileSize = function(size,byKB){
            if (size> 1024 * 1024&&!byKB){
                size = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            }
            else{
                size = (Math.round(size * 100 / 1024) / 100).toString() + 'KB';
            }
            return size;
        }
        //根据文件序号获取文件
        var getFile = function(index,files){
            for(var i=0;i<files.length;i++){       
              if(files[i].index == index){
                  return files[i];
                }
            }
            return false;
        }
        
        //将输入的文件类型字符串转化为数组,原格式为*.jpg;*.png
        var getFileTypes = function(str){
            var result = [];
            var arr1 = str.split(";");
            for(var i=0,len=arr1.length;i<len;i++){
                result.push(arr1[i].split(".").pop());
            }
            return result;
        }
        
        
        
        this.each(function(index,item){
            
            
            
            var _this = $(this);
            //先添加上file按钮和上传列表
            var instanceNumber =index;
            
            var inputStr = '';
             inputStr+='<div class="operate-btn">'
            inputStr += '<input id="select_btn_'+index+'" class="selectbtn"  style="display:none;" type="file" name="fileselect[]"';
            inputStr += option.multi ? ' multiple' : '';
            inputStr += ' accept="';
            inputStr += getFileTypes(option.fileTypeExts).join(",");
            inputStr += '"/>';
            inputStr += '<a id="file_upload_'+index+'-button" href="javascript:void(0)" class="uploadify-button">';
            inputStr += option.buttonText;
            inputStr += '</a>';
            inputStr += '<a id="file_upload_all_'+index+'-button" href="javascript:void(0)" class="uploadify-all-button">';
            inputStr += option.uploadbtnText
            inputStr += '</a>';
             inputStr+= '</div>';
            var uploadFileListStr = '<div id="file_upload_'+index+'-queue" class="uploadify-queue"></div>';
            _this.append(uploadFileListStr+inputStr);    
            
            
            //创建文件对象
          var fileObj = {
              fileInput: _this.find('.selectbtn'),                //html file控件
              uploadFileList : _this.find('.uploadify-queue'),
              url: option.uploader,                        //ajax地址
              fileFilter: [],                    //过滤后的文件数组
              filter: function(files) {        //选择文件组的过滤方法
                  
                  var arr = [];
                  var typeArray = getFileTypes(option.fileTypeExts);
                  
                  if(typeArray.length>0){
                      for(var i=0,len=files.length;i<len;i++){
                          var thisFile = files[i];
                      
                              if(parseInt(formatFileSize(thisFile.size,true))>option.fileSizeLimit){
                                  alert('文件'+thisFile.name+'大小超出限制!');
                                  continue;
                              }
                            if($.inArray(thisFile.name.split('.').pop(),typeArray)>=0){
                                arr.push(thisFile);    
                            }
                            else{
                                alert('文件'+thisFile.name+'类型不允许!');
                            }      
                        }    
                    }
                
                  return arr;      
              },
              //文件选择后
              onSelect: function(files){
                 
                    for(var i=0,len=files.length;i<len;i++){
                        var file = files[i];
                        
                        
                        //处理模板中使用的变量
                        var $html = $(option.itemTemplate.replace(/${fileID}/g,'fileupload_'+instanceNumber+'_'+file.index).replace(/${fileName}/g,file.name).replace(/${fileSize}/g,formatFileSize(file.size)).replace(/${instanceID}/g,_this.attr('id')));
                        
    //                    //如果是自动上传,去掉上传按钮
    //                    if(option.auto){
    //                        $html.find('.uploadbtn').remove();
    //                    }
                        //是否预览
                        if(option.preview){
                            //console.log(file.name.split('.').pop());
                            if(file.name.split('.').pop().toUpperCase() == "PNG" || file.name.split('.').pop().toUpperCase() == "JPG" || file.name.split('.').pop().toUpperCase() == "GIF" || file.name.split('.').pop().toUpperCase() == "JPEG" ||file.name.split('.').pop().toUpperCase() == "BMP" ){
                                //处理预览路径
                                 var path;  
                                    if(document.all)//IE  
                                    {  
                                       // imgFile.select();  
                                        path = document.selection.createRange().text;  
                                        var preview = '';
                                        preview +=     '<div id="img_upload_show_'+index+'_'+file.index+'" style="60px;height:60px;vertical-align:middle;display:inline-block;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled="true",sizingMethod="scale",src="" + path + "");">'
                                        preview +=       
                                        preview +=     '</div>'
                                       
                                       // document.getElementById("img_upload_show_"+index+"_"+file.index).style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src="" + path + "")";//使用滤镜效果        
                                    }  
                                    else//FF  
                                    {  
                                        path=window.URL.createObjectURL(file);// FF 7.0以上  
                                       
                                        
                                        var preview = '';
                                        preview +=     '<div id="img_upload_show_'+index+'_'+file.index+'" style="60px;height:60px;vertical-align:middle;display:inline-block">'
                                        preview +=       '<img id="img_show_'+index+'_'+file.index+'" src="'+path+'" width="60px" height="60px" />'
                                        preview +=     '</div>'
                                        //path = imgFile.files[0].getAsDataURL();// FF 3.0  
                                        
                                        // 
                                        //document.getElementById("img1").src = path;  
                                    }  
                                
                                $html.append(preview);
                                $html.find('#img_show_'+index+'_'+file.index).on('click',function(){
                                    
                                    var previewPath = $(this)[0].src;
                                    document.getElementById("preview_img").src = previewPath;
                                    $(".preview_model").show();
                                 });
                            }
    
                            
                        }
                        this.uploadFileList.append($html);
                        
                        //判断是否显示已上传文件大小
                        if(option.showUploadedSize){
                            
                            var num = '<span class="progressnum"><span class="uploadedsize">0KB</span>/<span class="totalsize">${fileSize}</span></span>'.replace(/${fileSize}/g,formatFileSize(file.size));
                            $html.find('.uploadify-content').append(num);
                        }
                        
                        //判断是否显示上传百分比    
                        if(option.showUploadedPercent){
                            var percentText = '<span class="up_percent">0%</span>';
                            $html.find('.uploadify-progress').after(percentText);
                        }
                        //判断是否是自动上传
                        if(option.auto){
                            this.funUploadFile(file);
                            $html.find('.uploadbtn').hide();
                        }
                        else{
                            $html.find('.uploadbtn').hide();
    //                        //如果配置非自动上传,绑定上传事件
                            
                                _this.find('.uploadify-all-button').on('click',(function(file){
                                    
                                 return function(){fileObj.funUploadFile(file);}
                                 
                             })(file));
    
                             
                        }
                        //为删除文件按钮绑定删除文件事件
                         $html.find('.delfilebtn').on('click',(function(file){
                                     return function(){fileObj.funDeleteFile(file.index);}
                                 })(file));
                     }
    
                 
                },                
              onProgress: function(file, loaded, total) {
    
                    var eleProgress = _this.find('#fileupload_'+instanceNumber+'_'+file.index+' .uploadify-progress');
                    var percent = (loaded / total * 100).toFixed(2) +'%';
                    if(option.showUploadedSize){
                        eleProgress.nextAll('.progressnum .uploadedsize').text(formatFileSize(loaded));
                        eleProgress.nextAll('.progressnum .totalsize').text(formatFileSize(total));
                    }
                    if(option.showUploadedPercent){
                        eleProgress.nextAll('.up_percent').text(percent);    
                    }
                    eleProgress.children('.uploadify-progress-bar').css('width',percent);
              },        //文件上传进度
    
              /* 开发参数和内置方法分界线 */
              
              //获取选择文件,file控件
              funGetFiles: function(e) {      
                  // 获取文件列表对象
                  var files = e.target.files;
                  
                  //继续添加文件
                  files = this.filter(files);
                  var fileFilterNames = [];
                  var filesNew =[];
                  for(var j=0;j<this.fileFilter.length;j++){
                        
                      fileFilterNames.push(this.fileFilter[j].name )
                      
                     }
                
                     for(var i=0,len=files.length;i<len;i++){
                        
                         if(fileFilterNames.indexOf(files[i].name) < 0 ){
                             this.fileFilter.push(files[i]);
                             filesNew.push(files[i]);
                             
                         }
                        
                     } 
                
                  this.funDealFiles(filesNew);
                  return this;
              },
              
              //选中文件的处理与回调
              funDealFiles: function(files) {
                  var fileCount = _this.find('.uploadify-queue .uploadify-queue-item').length;//队列中已经有的文件个数
                  for(var i=0,len=files.length;i<len;i++){
                      files[i].index = ++fileCount;
                      files[i].id = files[i].index;
                      files[i].isUpload = false;
                    
                      }
                  //执行选择回调
                  this.onSelect(files);
                  
                  return this;
              },
              
              //删除对应的文件
              funDeleteFile: function(index) {
                  for (var i = 0,len=this.fileFilter.length; i<len; i++) {
                          var file = this.fileFilter[i];
                          if (file.index == index) {
                              this.fileFilter.splice(i,1);
                              _this.find('#fileupload_'+instanceNumber+'_'+index).fadeOut();
                             
                              option.onCancel&&option.onCancel(file);    
                              break;
                          }
                          
                  }
                  return this;
              },
              
              //文件上传
              funUploadFile: function(file) {
                  var xhr = false;
                  try{
                     xhr=new XMLHttpRequest();//尝试创建 XMLHttpRequest 对象,除 IE 外的浏览器都支持这个方法。
                  }catch(e){      
                    xhr=ActiveXobject("Msxml12.XMLHTTP");//使用较新版本的 IE 创建 IE 兼容的对象(Msxml2.XMLHTTP)。
                  }
                  
                  if (xhr.upload) {
                      // 上传中
                      xhr.upload.addEventListener("progress", function(e) {
                          fileObj.onProgress(file, e.loaded, e.total);
                      }, false);
          
                      // 文件上传成功或是失败
                      xhr.onreadystatechange = function(e) {
                          if (xhr.readyState == 4) {
                              if (xhr.status == 200) {
                                  //校正进度条和上传比例的误差
                                  var thisfile = _this.find('#fileupload_'+instanceNumber+'_'+file.index);
                                  thisfile.find('.uploadify-progress-bar').css('width','100%');
                                    option.showUploadedSize&&thisfile.find('.uploadedsize').text(thisfile.find('.totalsize').text());
                                    option.showUploadedPercent&&thisfile.find('.up_percent').text('100%');
                                     _this.find('#fileupload_'+instanceNumber+'_'+file.index).find(".uploadify-content").css("color","#666");
                                  option.onUploadSuccess&&option.onUploadSuccess(file, xhr.responseText);
                                  //在指定的间隔时间后删掉进度条
                                  setTimeout(function(){
                                      _this.find('#fileupload_'+instanceNumber+'_'+file.index).find(".uploadify-progress").fadeOut();
                                      _this.find('#fileupload_'+instanceNumber+'_'+file.index).find(".up_percent").fadeOut();
                                      _this.find('#fileupload_'+instanceNumber+'_'+file.index).find(".delfilebtn").fadeOut();
                                      
                                  },option.removeTimeout);
                              } else {
                                  _this.find('#fileupload_'+instanceNumber+'_'+file.index).find(".uploadify-content").css("color","red");
                                  option.onUploadError&&option.onUploadError(file, xhr.responseText);        
                              }
                              option.onUploadComplete&&option.onUploadComplete(file,xhr.responseText);
                              //清除文件选择框中的已有值
                              fileObj.fileInput.val('');
                              file.isUpload = true;
                          }
                      };
          
                      option.onUploadStart&&option.onUploadStart();    
                      // 开始上传
                      xhr.open(option.method, this.url, true);
                      xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                      var fd = new FormData();
                      fd.append(option.fileObjName,file);
                      if(option.formData){
                          for(key in option.formData){
                              fd.append(key,option.formData[key]);
                          }
                      }
                      
                      xhr.send(fd);
                  }    
                  
                      
              },
              
              init: function() {      
                  //文件选择控件选择
                  if (this.fileInput.length>0) {
                      
                      this.fileInput.change(function(e) { 
                          
                          fileObj.funGetFiles(e); 
                      });    
                  }
                  
                  //点击上传按钮时触发file的click事件
                  _this.find('.uploadify-button').on('click',function(){
                      _this.find('.selectbtn').trigger('click');
                    });
                  
                  option.onInit&&option.onInit();
              }
          };
    
            //初始化文件对象
            fileObj.init();
        }); 
    }    
    
    })(jQuery)

    Huploadify.css

    @charset "utf-8";
    /* CSS Document */
    /* .uploadify-button{
        display:inline-block;
        margin:12px;
        border:1px solid #808080;
        background-color: #707070;
        line-height:24px;
        border-radius:12px;
        padding:0 18px;
        font-size:12px;
        font-weight: 600;
        font-family: '微软雅黑';
        color:#FFF;
        cursor:pointer;
        text-decoration:none;
    } */
    .uploadify-button:hover{
        background-color: #00a2d4;
    }
    .uploadfile{
        0;
        }
    .uploadify-queue .uploadify-queue-item{
        list-style-type:none;
        margin-top:10px;
        }
    .uploadbtn,.delfilebtn{
        display:inline-block;
        /* border:1px solid #999;
        line-height:24px;
        border-radius:4px; */
        padding:0 18px;
        font-size:12px;
        color:#666;
        cursor:pointer;
        background:url(./toolbars.png) repeat-x 0 0;
        text-decoration:none;
        }
    .up_filename,.progressnum,.delfilebtn,.uploadbtn,.up_percent{
        font-size:12px;
        color:#666;
        margin-left:10px;
        }
    .uploadify-progress{
         display:inline-block; 
         600px; 
         height:2px; 
         background-color:#badff8;
         border-radius:20px;
         /*border:2px groove #666;*/
         vertical-align:middle;
         padding:0;
         }
    .uploadify-progress-bar{
        0;
        height:100%;
        border-radius:20px;
        background-color: #0099FF;
        }
    /*8888888888888888*/
    
    .uploadStyle{
    position: relative;
    600px;
        padding: 20px 15px 15px;
        margin: 15px 0;
        background-color: #fafafa;
        box-shadow: inset 0 3px 6px rgba(0, 0, 0, .05);
        border-color: #e5e5e5 #eee #eee;
        border-style: solid;
        border- 1px 0;
        }
        .uploadify-bar {
        display:inline-block;
        260px;
        }
        .uploadify-progress-container {
          display:inline-block;
          200px;
        }
        .operate-btn {
        height:40px;
        }
    .uploadify-button,
    .uploadify-all-button{
      position: relative;
      float:right;
        display: inline-block;
        background: #00b7ee;
        padding: 8px 15px;
        margin-top: 10px;
        margin-left: 20px;
        color: #fff;
        text-align: center;
        border-radius: 4px;
        overflow: hidden;
        font-family: '微软雅黑';
        cursor:pointer;
        font-size:14px;
        text-decoration:none;
    }
    .uploadify-progress {
      150px;
    }
    .uploadify-queue .uploadify-queue-item {
       
        padding: 10px;
        border-bottom: 1px solid #ccc;
    }
    .uploadbtn {
       20px;
        height: 20px;
        margin-left:20px;
      background-position: 0px -150px;
    }
    .delfilebtn {
       10px;
        height: 22px;
    background-position: 0px -190px;
      
    }
    .up_percent {
    display:inline-block;
    24px;
    }
    .uploadify-progress {
    height:10px;
    }
    .uploadify-progress-bar {
    height:10px;
    }
    .uploadify-content {
    display:inline-block;
    margin-right:10px;
         240px;
    }
    
    .preview_model{
        display:none;
        position: absolute;
         100%;
        height: 150%;
        top: 0;
        left:0;
        min-height:100%;
        min-100%;
        background-color: rgba(0,0,0,0.5);
        }
        .preview_model_container {
             
         800px;
        height: 500px;
        margin: 100px auto;
        text-align: center;
        margin-bottom: 0;
        overflow: auto;
        }
       #preview_img {
        /* position: absolute;
        top: 20%;
        left: 33%; */
        }
  • 相关阅读:
    shell中逻辑与的两种表示方法
    Git学习之Git恢复进度
    RH318之域控服务器
    《征服C指针》读书笔记
    2013年:一个技术领导的启程
    sqlite的一个Unable to Open database file的坑爹错误
    我的2013——青春的躁动
    C/C++注册动态对象到Lu系统并进行运算符重载
    Geeks面试题:Min Cost Path
    Leetcode Gray Code
  • 原文地址:https://www.cnblogs.com/candice-cc/p/6428736.html
Copyright © 2020-2023  润新知