要拦截粘贴事件,再读取文件,有两种方法获取文件
方法一: 读取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