element upload组件,ctrl v粘贴图片自动上传

产品提了一个需求,需要用户可以在微信或者qq截屏之后,ctrl v直接上传图片,网上查了几篇文章参考了其中一篇实现了
参考文章:https://blog.csdn.net/rencaishigepi/article/details/80277810
代码↓

<el-upload
  drag
  class="upload-demo"
  :on-preview="handlePictureCardPreview"
  :on-success='handleSuccess'
  :on-remove='handleRemove'
  list-type="picture-card"
  :action="uploadUrl"
  :file-list="fileList"
  ref='upload'
  >
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
/* base64转file */
dataURLtoFile (dataurl, filename) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
  while(n--){
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {type:mime})
},

/* 处理粘贴事件 */
handlectrlvEvent (e) {
  if (!this.ctrlvFlag) return
  this.ctrlvFlag = false

  let arr = this.fileList
  let imgs = arr.map(item => {return item.url})
  let length = [...new Set(imgs)].length
  
  if (length >= this.limit) {
    this.$message.error('上传图片超出限制,最大允许上传' + this.limit + '张图片') 
    this.ctrlvFlag = true
    return
  }

  let clipboardData = e.clipboardData

  let items = clipboardData.items

  let item = null

  if (items && items.length) {
    for (let i = 0; i < clipboardData.types.length; i++) {
      if (clipboardData.types[i] === 'Files') {
        item = items[i]
        break
      }
    }
  }

  if (item && item.kind == 'file' && item.type.match(/^image\//i)) {
    const reader = new FileReader()
    reader.readAsDataURL(item.getAsFile())
    reader.onload = () => {
      let name = Date.now()
      let file = this.dataURLtoFile(reader.result, name)

      this.fileList.push({name: name, url: reader.result})

      this.uploadImage(file)
    }
  }
},

/* 手动上传图片 */
uploadImage (file) {
  var fd = new FormData()
  fd.append("file", file)

  this.$http.post(this.uploadUrl, fd, {FORMDATA: true, form:'fileUpload'}).then(res => {
    if (res.data.code == 200) {
      this.fileList.forEach(item => {
        if (item.name == file.name) {
          item.url = this.imgShow + res.data.data[0]
        }
      })

      this.fileList.forEach(item => {
        if (!this.fileList.filter(el => el.name == item.name).length) {
          this.fileList.push(item)
        }
      })
    }

    setTimeout(() => {
      this.ctrlvFlag = true
    }, 1000)
  })
}
mounted () {
  document.addEventListener('paste', this.handlectrlvEvent)
},

beforeDestroy () {
  document.removeEventListener('paste', this.handlectrlvEvent)
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值