diff --git a/src/components/richtext/rich-edit.vue b/src/components/richtext/rich-edit.vue index 1a58176..7425c0d 100644 --- a/src/components/richtext/rich-edit.vue +++ b/src/components/richtext/rich-edit.vue @@ -75,13 +75,99 @@ const handleCreated = (editor) => { const customPaste = (editor, event, callback) => { let htmlData = event.clipboardData.getData('text/html') // 获取粘贴的 html + console.log(htmlData) + let rtfData = event.clipboardData.getData('text/rtf') // 获取粘贴的 html + console.log('-------------- rtfData --------------', rtfData) + htmlData = htmlData.replace(/<\/?span[^>]*>/g, ''); htmlData = htmlData.replace(']*src=['"]([^'"]+)[^>]*>/g); + // 如果有 + if (imgSrcs && Array.isArray(imgSrcs) && imgSrcs.length) { + console.log('imgSrcs', imgSrcs) + // 从rtf内容中查找图片数据 + const rtfImageData = extractImageDataFromRtf(rtfData); + console.log('rtfImageData', rtfImageData) + // 如果找到 + if (rtfImageData.length) { + // TODO:此处可以将图片上传到自己的服务器上, + + // 执行替换:将html内容中的img标签的src替换成ref中的图片数据,如果上面上传了则为图片路径 + htmlData = replaceImageFile(htmlData, imgSrcs, rtfImageData) + console.log('+++++++++++++++++++ replace after +++++++++++++++++++', htmlData) + } + } + editor.dangerouslyInsertHtml(htmlData); event.preventDefault() callback(false) } +/** + * 从rtf内容中匹配返回图片数据的集合 + * @param rtfData + * @return Array + */ +const extractImageDataFromRtf = (rtfData) => { + if (!rtfData) { + return []; + } + const regexPictureHeader = /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/ + const regexPicture = new RegExp('(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}', 'g') + const images = rtfData.match(regexPicture) + const result = ref([]) + if (images) { + for (const image of images) { + const imageType = ref(false) + if (image.includes('\\pngblip')) { + imageType.value = 'image/png' + } else if (image.includes('\\jpegblip')) { + imageType.value = 'image/jpeg' + } + if (imageType.value) { + result.value.push({ + hex: image.replace(regexPictureHeader, '').replace(/[^\da-fA-F]/g, ''), + type: imageType.value + }); + } + } + } + return result.value; +} + +/** + * 将html内容中img标签的属性值替换 + * @param htmlData html内容 + * @param imageSrcs html中img的属性src的值的集合 + * @param imagesHexSources rtf中图片数据的集合,与html内容中的img标签对应 + * @param isBase64Data 是否是Base64的图片数据 + * @return String + */ +const replaceImageFile = (htmlData, imageSrcs, imagesHexSources, isBase64Data = true) => { + if (imageSrcs.length === imagesHexSources.length) { + for (let i = 0; i < imageSrcs.length; i++) { + const newSrc = isBase64Data + ? `` + : imagesHexSources[i] + htmlData = htmlData.replace(imageSrcs[i], newSrc); + } + } + return htmlData; +} + +/** + * 十六进制转base64 + */ +const convertHexToBase64 = (hexString) => { + return btoa(hexString.match(/\w{2}/g).map(char => { + return String.fromCharCode(parseInt(char, 16)); + }).join('')); +} + + watch(() => props.modelValue, () => { valueHtml.value = props.modelValue })