javascirpt封装xhr上传多张图片,以及解决formdata后端只接受一张图片问题,用原型链来封装减少资源浪费和提高性能

这里使用了函数的原型链来封装每个共享函数和特权方法 访问私有数据

<html>
    <head>
        <meta http-equiv="Content-Type:text/html;charset=utf-8"/>
        <title>title>
        <script type="text/javascript" src="common.js">script>
        <style type="text/css">
           #preview
            {
                display: flex;
                flex-wrap: wrap;
                width: 580px;
                padding: 10px;
                justify-content: start;
            }
            .icon-po 
            {
                overflow: hidden;
                position: relative;
                width: 150px;
                height: 150px;
                margin-right: 20px;
                margin-top: 20px;
            }
            .icon-close 
            {
                position: absolute;
                right: 5%;
                top: 5%;
                width: 30px;
                border-radius: 45%;
                background-color: #fff;
                color: #000;
                font-size: 16px;
                line-height: 1.87em;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .pic 
            {
                width:150px;
                height: 150px;
            }
        style>

    head>
    <body>
        <div id="container">
            <input type="file" name="uploadimg" id="upimg" multiple/>
            <input type="button" value="预览" name="icon" id="prebut"/>
            <input type="button" value="上传" id="upxhr"/>
        div>
        <div id="preview">div>
        <script type="text/javascript">
          
          
         
		//添加函数原型链的addMethods()方法
        Function.prototype.addMethods=function(name,fn)
        {
          this.prototype[name]=fn;
        }
        //创建上传函数
        var uploadImg=function(){
          var fL=[];
          var url=[];
          var name=[];
          var e=0;
          //以下为特权方法函数,方便获取私有数据
          this.getfL=function(){
            return fL;
          };
          this.getUrl=function(){
            return url;
          };
          this.getName=function(){
            return name;
          };
          this.setfL=function(val){
            fL.push(val)
          };
          this.setName=function(val)
          {
            name.push(val);
          }
          this.setUrl=function(val)
          {
            url.push(val);
          }
          this.getThis=function()
          {
            
            return this;
          }
          this.getEle=function(ele)
          {
            return document.getElementById(ele);
          }
          this.clearfL=function()
          {
            //清空数组时,也应该清空name数组,避免重新添加图片时弹出已经添加该图片
            fL=[];
            name=[];
            url=[];
          }
          this.clearName=function()
          {
            name=[];
          }
          this.clearUrl=function(){
            url=[];
          };
        };
        //以下都是原型链函数
        uploadImg.addMethods('getfL',function(){
          
          return this.getfL();
        });
        
        uploadImg.addMethods('getFiles',function(upfiles){
          if(upfiles.length>0 && upfiles.length<6)
          {
            for(var i=0,len=upfiles.length;i<len;i++)
            {
              if(/image\/(jpe?g|png|gif)/.test(upfiles[i].type))
              {
                if(upfiles[i].size<1024*1000)
                {
                  if(this.getfL().length==0)
                  {
                    this.setfL(upfiles[i]);
                   
                  }else if(this.getfL().length>0)
                  {
                    for(var x=0,leng=this.getfL().length;x<leng;x++)
                    {
                      
                      this.setName(this.getfL()[x].name);
                      
                    }
                    
                    if(this.getName().indexOf(upfiles[i].name)==-1)
                    {
                      this.setfL(upfiles[i]);
                      this.setName(upfiles[i].name);
                    }else
                    {
                      alert('此图片已经添加');
                    }
                  }

                  if(this.getfL().length>5)
                  {
                    this.clearfL();
                    alert('最大上传5张图片,请重新选择图片');
                    
                  }
                }else
                {
                  alert('请上传小于1M的图片');
                }
              }else
              {
                alert('请上传正确的图片类型');
              }
            }
          }else
          {
            alert('最大上传5张图片');
          }
        });

        uploadImg.addMethods('preView',function(){
          var e=0;
          var that=this.getThis();
          this.getfL().forEach(function(item,index,array){
            //创建异步读取文件对象
            var reader=new FileReader();
            //创建div1为图片预览小容器,div2为关闭div1小容器的按钮
            var div1=document.createElement('div');
            var div2=document.createElement('div');
            //为他们添加样式名称
            div1.className="icon-po";
            div2.className="icon-close";
            div2.innerHTML='X';
            div1.index=div2.index=e;
            e++;

            reader.onload=function(){
              var img=new Image();
              img.src=reader.result;
              img.title=item.name;

              //检查是否已经添加该图片的url连接在预览中
              var pos=that.getUrl().indexOf(img.src);
              
              if(pos==-1)
              {
                that.setUrl(img.src);
                
                div1.appendChild(img);
                div1.appendChild(div2);
                that.getEle('preview').appendChild(div1);
              }
              else
              {
                return;
              }
              div2.onclick=function(event){
                var ex=event.target;
                div1.remove();
                //移除div1里面图片时,同时移除图片对象数组、URL数组、和图片名字数组中的相关图片数据
                that.getfL().splice(index,1);
                that.getUrl().splice(index,1);
                that.getName().splice(ex.index,1);
                //index--;
                //unique()为自己的数组去重数组
                var imname=unique(that.getName());
                if(that.getfL().length != imname.length)
                {
                  that.clearName();
                  
                  that.getfL().forEach(function(item,index,array){
                    that.setName(item.name);
                    
                  });
                }
               
                
              };

            };
            reader.readAsDataURL(item);
          });
        });

        uploadImg.addMethods('xhrup',function(){
          var xhr=new createXHR();
          
          if(this.getfL().length>0)
          {
            var fd=new FormData();
            var t=this.getThis();

            for(var i in this.getfL())
            {
              fd.append(i,this.getfL()[i]);
              xhr.open('post','ajaxvalidationimg.php',true);
              xhr.send(fd);
            }

            xhr.onload=function(){
              if(xhr.status==200)
              {
                var responseText=xhr.responseText;
                if(!/[\[\S*]]/.test(responseText))
                {
                  alert(responseText);
                }else
                {
                  var textarr=responseText.split('\t\n');
                  textarr.pop();
                  for(var x=0,l=textarr.length;x<l;x++)
                  {
                    var m=JSON.parse(textarr[x]);
                  }
                }
                alert(m.msg);
                console.log(m.data);
              }
              else
              {
                alert('xhr获取数据失败');
              }
              
            };
            t.clearfL();
          }else
          {
            alert('没有可上传的图片');
          }

        });

        var upload=new uploadImg();
        
        var file=document.getElementById("upimg");
       file.onchange=function(){
          upload.getFiles(file.files);
          upload.preView();
          console.info(upload.getfL());
       };

       upload.getEle('prebut').onclick=function(){
          var preview=upload.getEle('preview');
          var d=document.defaultView.getComputedStyle(preview,null);
          if(d.display!="none")
          {
            preview.style.display='none';
          }else
          {
            preview.style.display="flex";
          }
          if(preview.children.length==0)
                {
                  upload.clearfL();
                  alert('无图片可预览');
                } 
       };

       upload.getEle('upxhr').onclick=function(){
        upload.xhrup();
        upload.getEle('preview').innerHTML='';
        
       };
       

        
       script> 
    body>
html>

你可能感兴趣的:(javascript学习日记,javascript,前端,开发语言)