主要的知识点是,浏览的paste
事件,clipboardData
。
paste
一个标准的Dom事件,粘贴事件,会在用户按下Ctrl+v
,或者通过鼠标复制时触发.像其他事件一样,我们可以通过addEventListener
为一个Element
添加一个粘贴事件的监听函数 如以下代码。
document.addEventListener('paste', (event) => {
// 阻止默认事件和冒泡行为
pe.preventDefault()
pe.stopPropagation()
// 真正的黏贴事件
console.log('粘贴事件', event)
});
文章来源地址https://www.toymoban.com/news/detail-554004.html
我使用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
})
}
})
实际使用效果:
文章来源:https://www.toymoban.com/news/detail-554004.html
到了这里,关于Vue中实现图片黏贴上传到服务器:功能分析和实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!