实例:实现拖拽及上传图片

实例效果


代码如下:

<div id="leftContain" style="width: 90%;height: 90%"> 
    <img  id="img" class="img" align="center" src="">  
    <input  type="file" @change="uploadImg($event)" ref="img" style="opacity: 0"/>
</div>
<div style="float: right;margin-right: 8%">
    <span class="imgName" style="font-size: 5px">未选择图片</span>
    <el-button size="medium" type="primary" @click="toCheck"  round>提交识别</el-button>
</div>

主要部分讲解

  • div(id=“leftContain”):为拖拽点击及最终图片显示的方框
  • img(id=“img”):最终显示图片的位置
  • input:为点击上传本地图片的组件(设置与img重合,且透明度为0)

起初图片:在这里插入图片描述


css代码:

		#leftContain{
            border:1px solid #DCDCDC;
            box-shadow: 0px 0px 4px 3px rgb(245,245,245);
            width: 48%;
            height: 90%;
            display: inline-block;
            margin-top: 2.5%;
            margin-left: 20px;
            float: left;
            position: relative;
        }
        #leftContain img {
            width: 85%;
            height: 85%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-55%);
        }
        #leftContain input {   /*与#leftContain img一样*/
            width: 85%;
            height: 85%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-55%);
        }

逻辑代码:
mounted():

let dropbox = document.querySelector('.img');
dropbox.addEventListener('dragenter', this.onDrag, false);
dropbox.addEventListener('dragover', this.onDrag, false);
dropbox.addEventListener('drop', this.onDrop, false);

methods:

onDrag: function(e) {
  e.stopPropagation();
  e.preventDefault();
},
onDrop: function(e) {
  e.stopPropagation();
  e.preventDefault();
  let dt = e.dataTransfer;
  document.querySelector('.imgName').innerHTML = imgfile.files[0].name;
  let reader = new FileReader();
  reader.readAsDataURL(dt.files[0]);
  reader.onload = function() {
  document.querySelector('img').src = this.result;
  };
  this.file = e.target.files;
},
uploadImg(e) {
  let imgfile = this.$refs.img;
  let reader = new FileReader();
  reader.readAsDataURL(imgfile.files[0]);
  document.querySelector('.imgName').innerHTML = imgfile.files[0].name;
  reader.onload = function() {
  document.querySelector('img').src = this.result;
  };
  this.file = e.target.files;
}

参考:https://www.jb51.net/article/135277.htm


完成!!!


End

Logo

前往低代码交流专区

更多推荐