tinymce富文本粘贴上传图片
initTinymce() {
const _this = this
window.tinymce.init({
xxx..
paste_data_images: false, // 粘贴图片
xxx...
init_instance_callback: editor => {
xxx...
editor.on('paste', (evt) => {
// 监听粘贴事件
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('图片上传失败,联系开发人员')
}
})
} 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,//隐藏底部状态栏
// 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
// // 监听粘贴事件
// // 实现图片粘贴上传
// 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>