用户截图,并在网页上粘贴,前端读取剪切板里的图片

要拦截粘贴事件,再读取文件,有两种方法获取文件

方法一: 读取window.navigator对象里的clipboard

document.addEventListener('paste', async (e) => {
  const clipboardItems = await navigator.clipboard.read()
  const fileList: File[] = []
  const urlList: string[] = []
  for (const clipboardItem of clipboardItems) {
    for (const type of clipboardItem.types) {
      // 筛选图片类型的文件
      if (type.indexOf('image') > -1) {
        const blob = await clipboardItem.getType(type)
        // 将Blob转换成File
        const file = new File([blob], `image-${Date.now()}`, { type: type })
        fileList.push(file)
        // 将Blob转换成url,方便前端展示预览图
        const url = URL.createObjectURL(blob)
        urlList.push(file)
      }
    }
  }
  console.log(fileList, urlList)
});

方法二: 读取粘贴事件的event对象里的clipboardData

document.addEventListener('paste', (event: ClipboardEvent) => {
  if (!event.clipboardData?.files) {
    return
  }
  const fileList: File[] = []
  const urlList: string[] = []
  const clipboardFiles = event.clipboardData.files
  for (let i = 0; i < clipboardFiles.length; i++) {
    if (clipboardFiles[i].type.indexOf('image') > -1) {
      fileList.push(clipboardFiles[i])
      const url = URL.createObjectURL(blob)
      urlList.push(file)
    }
  }
  console.log(fileList, urlList)
})

两个方法的区别在于:如果我们把文件粘贴到iframe里面去(比如富文本编辑器Tinymce),那么使用方法二,将无法正确读取到文件,而方法一则不受限制,因此,更推荐使用方法一。

参考文章 https://www.jb51.net/article/212396.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值