tinymce富文本粘貼上傳圖片
initTinymce() {
const _this = this
window.tinymce.init({
xxx..
paste_data_images: false, // 粘貼圖片
xxx...
init_instance_callback: editor => {
xxx...
editor.on('paste', (evt) => {
// 監(jiān)聽粘貼事件
this.onPaste(evt)
})
},
xxx...
})
},
onPaste(event) {
// 實現圖片粘貼上傳
const items = (event.clipboardData || window.clipboardData).items
// 搜索剪切板items 只取第一張
if (items[0].type.indexOf('image') !== -1) {
console.log('粘貼的是圖片類型')
const file = items[0].getAsFile()
const formData = new FormData()
formData.append('file', file)
// 上傳圖片
UpLoadImg(formData).then(res => {
console.log(res)
if (res.code === 200) {
// 放到內容當中 (圖片正常上傳沒問題)
window.tinymce.get(this.tinymceId).insertContent(`<img class="wscnph" src="${res.data.image}" >`)
} else {
this.$message.error('圖片上傳失敗,聯系開發(fā)人員')
}
})
} else {
console.log('粘貼的不是圖片旱爆,不能上傳')
}
}
比較完整的例子,粘貼和工具欄上傳圖片自赔,都會走images_upload_handler
<script lang="jsx">
import { onMounted } from 'vue';
import {commonService} from '@/request'
export default {
setup() {
let tinymceInstance
onMounted(() => {
tinymce.init({
selector: '#mytextarea',
language: 'zh_CN',
branding: false,
resize: false,//禁止改變大小
statusbar: false,//隱藏底部狀態(tài)欄
// width: 600,
// height: 300,
plugins: [
'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak',
'searchreplace', 'wordcount', 'visualblocks', 'code', 'fullscreen', 'insertdatetime', 'media',
'table', 'emoticons', 'template', 'help'
],
toolbar: 'undo redo | styles | bold italic link forecolor backcolor emoticons | alignleft aligncenter alignright alignjustify | ' +
'bullist numlist outdent indent | image media print preview fullscreen',
menubar: 'favs file edit view insert format tools table help',
content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px }',
init_instance_callback: editor => {
tinymceInstance = editor
editor.setContent(`22`)
},
paste_data_images: true, // 允許粘貼圖片
// init_instance_callback: editor => {
// editor.on('paste', (event) => {
// debugger
// // 監(jiān)聽粘貼事件
// // 實現圖片粘貼上傳
// const items = (event.clipboardData || window.clipboardData).items
// // 搜索剪切板items 只取第一張
// if (items[0].type.indexOf('image') !== -1) {
// console.log('粘貼的是圖片類型')
// const file = items[0].getAsFile()
// commonService.upload({file, bizType: 'Approval'}).then(data => {
// editor.insertContent(`<img src="${commonService.getFileUrl(data.readPath)}" />`)
// })
// } else {
// console.log('粘貼的不是圖片,不能上傳')
// }
// })
// },
images_upload_handler: async function (blobInfo, success, failure, progress) {
debugger
const file = blobInfo.blob()
const data = await commonService.upload({file, bizType: 'Approval'})
return commonService.getFileUrl(data.readPath)
},
})
})
function getContent() {
console.log('tinymceInstance.getContent()', tinymceInstance.getContent())
}
return () => <>
<textarea id="mytextarea" style={{ height: '80%' }}>
</textarea>
<ElButton onClick={getContent}>獲取內容</ElButton>
</>
}
}
</script>