主要的知识点是,浏览的paste
事件,clipboardData
。
paste
一个标准的Dom事件,粘贴事件,会在用户按下Ctrl+v
,或者通过鼠标复制时触发.像其他事件一样,我们可以通过addEventListener
为一个Element
添加一个粘贴事件的监听函数 如以下代码。
document.addEventListener('paste', (event) => {
// 阻止默认事件和冒泡行为
pe.preventDefault()
pe.stopPropagation()
// 真正的黏贴事件
console.log('粘贴事件', event)
});
我使用vue3,在页面初始化的时候,就绑定这个监听事件,全局监听页面上的黏贴事件,然后通过读取内容,将文件上传到服务器中,也支持微信截图上传:
// 图片黏贴上传功能
document.addEventListener('paste', (pe) => {
pe.preventDefault()
pe.stopPropagation()
fileList.push(1)
console.log('粘贴事件---', pe)
var data = pe.clipboardData!.files[0]
console.log('fun', data);
if (!data) {
return
}
var date = new Date()
var reader = new FileReader();
var uploadType = getType(data.type, data)
reader.readAsDataURL(data);
reader.onload = function (event) {
console.log("加載成功-", event);
// 用于预览图片
var uploadFileRaw = reactive({
name: data.lastModified + data.name,
path: uploadType === 'picture' ? event!.target!.result as string : "",
type: uploadType,
size: (data.size / 1024 / 1024).toFixed(2).toString() + "M",
sha: "",
openLink: '',
downLink: '',
htmlLink: '',
creatTime: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`,
selected: false,
showTips: false,
uploading: true,
})
gitFileList.push(uploadFileRaw)
// 用于上传图片
fileApi.uploadFile(`${filePath.value}/${data.lastModified + data.name}`, {
"message": "Upload From FileHub",
"content": (event!.target!.result! as string).split("base64,")[1]
}).then((res: any) => {
console.log("上传文件返回:", res);
if (res.status === 201) {
uploadFileRaw.uploading = false
uploadFileRaw.path = res.data.content.path
uploadFileRaw.sha = res.data.content.sha
uploadFileRaw.openLink = uploadType === 'picture' ? `${uStore.fileCdn}${res.data.content.path}` : `${uStore.gitIoCdn}/${res.data.content.path}`
uploadFileRaw.downLink = uploadType === 'picture' ? `${uStore.fileCdn}${res.data.content.path}` : `${uStore.gitIoCdn}/${res.data.content.path}`
uploadType === 'picture' && imgPreList.push(`${uStore.fileCdn}${res.data.content.path}`)
console.log("上传文件结果:", res, imgPreList)
} else {
ElMessage.error("上传失败:" + res.data.message)
gitFileList.splice(gitFileList.indexOf(uploadFileRaw), 1)
}
upPropress.value = 1
fileList.length = 0
}).catch(error => {
uploadFileRaw.sha = 'error'
gitFileList.splice(gitFileList.indexOf(uploadFileRaw), 1)
console.log("上传文件错误:", error);
upPropress.value = 1
fileList.length = 0
})
}
})
实际使用效果: