需求
页面中上传图片,每次都下载后从文件内选择太麻烦,想要直接复制粘贴上传
已有功能element-upload上传
页面form中已使用upload实现点击上传功能
关键方法
粘贴监听事件
window.addEventListener('paste', handlePaste)
监听事件获取粘贴对象,其中通过getAsFile读出对象
const handlePaste = async (evt: any) => {
const items: Iterable | undefined = evt.clipboardData?.items as Iterable
// 这是一个类数组对象!!!不是数组,不能用map和forEach遍历
// 可以用for...of 遍历是因为其内部实现了可迭代协议
if (items) {
for (const item of items) {
// 这一步很重要,直接把item打印出来是看不到具体内容的,需要遍历它
if (item.kind === 'file') {
// 取得文件对象
pasteFile = item.getAsFile()
}
}
// 此时pasteFile为粘贴中已取得对像,下面逻辑根据自身业务来
if (pasteFile && getBeforeUpload('image', 10)(pasteFile)) {
const imageUrl = await getClipHttpRequest('questionOrder')({ file: pasteFile } as UploadRequestOptions)
if (formInstance) {
formInstance.values.imgUrls = [...(formInstance.values.imgUrls ?? []), { url: imageUrl, response: imageUrl }]
}
}
}
}
注意
此方法以来粘贴监听,如果有多个上传,需自行处理