vue 图片上传

拖动上传代码

<template>
  <div class="home">
    <div id="box" @drop="getDropImg " @dragover="addEventListener"></div>
  </div>
</template>
<script>
export default {
  name: 'Home',
  data() {
    return {
      imageUrl: [],
      fileList: [],
    }
  },
  methods: {
    // 先阻止浏览器默认的打开文件事件
    addEventListener(e) {
      e.stopPropagation();
      e.preventDefault();
      e.dataTransfer.dropEffect = 'copy';
    },
    getDropImg(e) {
      e.stopPropagation();
      e.preventDefault();
      this.fileList.push(...e.dataTransfer.files)
      console.log(e.dataTransfer.files)//获取到上传的图片参数
      this.fileList.forEach(item => {
        this.getBase64(item).then(res => {
          console.log(res)
          this.image.push(res)
        })
      })
    },
    // 将file对象转换为Base64数据 可以放在img标签内显示
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    }
  },
}
</script>
<style scoped>
#box {
  width: 100vw;
  height: 100vh;
  border: 1px solid #000
}
</style>

点击上传

<template>
  <div class="home">
    <!--  设置multiple可一次性上传多个文件  -->
    <input type="file" name="avatar" multiple accept="image/gif,image/jpeg,image/jpg,image/png" style="display:none" @change="changeImage($event)" ref="avatarInput">
    <button @click="fileListData">queding</button>
  </div>
</template>
<script>
export default {
  name: 'Home',
  data() {
    return {
      imageUrl: [],
      fileList: [],
    }
  },
  methods: {
    fileListData() {
      this.$refs.avatarInput.click()
    },
    changeImage(e) {
      console.log(e.target.files)//获取到了文件的file对象
      this.$refs.avatarInput.value = ""// 上传完成清除input内数据
    },
  }
}
</script>

本文参考 https://cloud.tencent.com/developer/article/1487515?from=information.detail.js+阻止拖拽

posted @ 2021-05-28 10:35  云鹤^  阅读(65)  评论(0)    收藏  举报