在使用富文本编辑器时,通常 word 整体粘贴时,图片总是无法正常显示,图片地址会是 src=”//0”的情况,这主要时因为,我们整体粘贴时,实际上我我们粘贴过去的是一片 word 的 dom 字符串,其中编辑器会为我们过滤其他无用标签,保留了主要部分。由于粘贴时候 word 文档中图片部分实际上引用的是本地地址,由于浏览器和 js 限制无法读取或者操作本地文件,因此无法正常显示。如果是网络上复制粘贴的文档则可以正常显示。
一下是从 word 直接粘贴过来的效果
一下是从网络上粘贴过来的效果
let quill = this .$refs.myQuillEditor.quill; quill.root.addEventListener( "paste" , (evt) => { if ( evt.clipboardData && evt.clipboardData.files && evt.clipboardData.files.length ) { evt.preventDefault(); [].forEach.call(evt.clipboardData.files, (file ) => { if (!file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i )) { return ; } console .log('单个图片粘贴' , file); const reader = new FileReader() reader.readAsDataURL(file) reader.onload = (e ) => { quill.insertEmbed( quill.getSelection().index, "image" , reader.result ) } reader.onerror = (error ) => reject(error) }); }
function 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 = []; if (images) { for (const image of images) { let imageType = false ; if (image.includes("\\pngblip" )) { imageType = "image/png" ; } else if (image.includes("\\jpegblip" )) { imageType = "image/jpeg" ; } if (imageType) { result.push({ hex: image .replace(regexPictureHeader, "" ) .replace(/[^\da-fA-F]/g , "" ), type: imageType, }); } } } return result; }
function convertHexToBase64 (hexString ) { return btoa( hexString .match(/\w{2}/g ) .map((char ) => { return String .fromCharCode(parseInt (char, 16 )); }) .join("" ) ); }
富文本编辑器 word 整体粘贴实现图片自动展示(一)
缺失模块。
1、请确保node版本大于6.2
2、在博客根目录(注意不是yilia-plus根目录)执行以下命令:
npm i hexo-generator-json-content --save
3、在根目录_config.yml里添加配置:
jsonContent:
meta: false
pages: false
posts:
title: true
date: true
path: true
text: false
raw: false
content: false
slug: false
updated: false
comments: false
link: false
permalink: false
excerpt: false
categories: false
tags: true