代碼地址:https://github.com/hanghang2/tinymce-pastewordimage,擼碼不宜給顆小星星吶!
tinymce 4和5版本有powerpaste復(fù)制word圖片,但是不支持wps軟件,看了幾款富文本都沒有支持wps和office粘貼保留圖片的,于是乎決定自己做一款。
原生的paste事件中,可以獲取到用戶的粘貼信息,走入誤區(qū)的我看到了text/html的信息有圖片信息,地址是file:///xxx 的地址,瀏覽器安全策略限制,js無法訪問客戶端的這些文件,于是乎陷入了困境。
后續(xù)查到粘貼的text/rtf內(nèi)容中有16進(jìn)制的圖片信息,于是便有了解決辦法:把數(shù)據(jù)中的16進(jìn)制圖片信息轉(zhuǎn)換為base64,然后替換頁面的圖片路徑即可實現(xiàn)word的復(fù)制粘貼,于是乎做了一款tinymce 6版本的word粘貼插件,使用方法和源碼地址:https://github.com/hanghang2/tinymce-pastewordimage
tinymce6 pastewordimage插件
一款從word粘貼到富文本框圖片正常顯示插件,wps和office都可以正常復(fù)制粘貼圖片
使用步驟:
第一步:把當(dāng)前plugins目錄下的pastewordimage文件夾拷貝到你的項目tinymce/plugins目錄下去;
例如react項目,路徑為 項目根目錄/public/tinymce/plugins/
第二步:tinymce初始化init配置plugins參屬下增加pastewordimage;
例如:
// 如下增加pastewordimage參數(shù)
<Editor
init={{
branding: false, // 去掉右下角的水印
menubar: true, // 菜單欄
height: 500,
plugins: [
'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount', 'codesample',
'pastewordimage', // word復(fù)制圖片插件
],
}}
initialValue="<p>This is the initial content of the editor.</p>"
onInit={(evt, editor) => editorRef.current = editor}
rootClassName={style.editor}
/>
第三步:版當(dāng)前項目的tinymce.min.js文件拷貝到項目的tinymce目錄中進(jìn)行覆蓋;
解釋:
// 源碼中 wps粘貼單個圖片時候粘貼的內(nèi)容中會有text/html類型,導(dǎo)致getDataTransferItems函數(shù)返回結(jié)果不正確;
// 修改如下:items[contentType]賦值增加判斷;
const getDataTransferItems = dataTransfer => {
const items = {};
if (dataTransfer && dataTransfer.types) {
for (let i = 0; i < dataTransfer.types.length; i++) {
const contentType = dataTransfer.types[i];
try {
// items[contentType] = dataTransfer.getData(contentType);
items[contentType] = dataTransfer.types.indexOf('Files') === -1 ? dataTransfer.getData(contentType) : ''; // wps粘貼單個圖片問題處理
} catch (ex) {
items[contentType] = '';
}
}
}
return items;
};