背景
最近在开发使用editor.md编辑,记录一下修改上传图片逻辑,使用阿里云oss自定义上传图片
安装使用
editor.md 官网地址查看相关使用
使用npm install 安装有问题,很多资源引入有问题,后来改成下面的资源直接引入方式
1、直接下载zip解压在项目里public/static
里,最后做一些资源修改,如下图

2、下载jQuery
下载地址:www.jsdelivr.com/package/npm...
下载后放入editor.md
根目录下,如上图
3、下载scriptjs
css
cnpm install --save scriptjs
4、组件实现

editor.md.config.js
相关实现如下
js
import { ossUpload } from '@/utils/ossUpload'
const defaultConfig = {
width: '100%',
height: '100%',
// autoHeight: true,
path: '/static/editor.md/lib/',
// theme: 'dark',
// previewTheme: 'dark',
// editorTheme: 'pastel-on-dark',
markdown: '', // 默认填充内容
lineWrapping: true, // 编辑框不换行
codeFold: true, // 代码折叠
placeholder: '请输入...',
syncScrolling: true,
saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
searchReplace: true,
watch: true, // 实时预览
htmlDecode: 'style,script,iframe|on*', // 开启 HTML 标签解析,为了安全性,默认不开启
toolbarIcons: function() {
return [
'undo', 'redo', '|',
'bold', 'del', 'italic', 'quote', 'ucwords', 'uppercase', 'lowercase', '|',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', '|',
'list-ul', 'list-ol', 'hr', '|',
'link', 'reference-link', 'image', 'code', 'preformatted-text', 'code-block', 'table', 'datetime', 'pagebreak', '|',
'goto-line', 'watch', 'preview', 'fullscreen', 'clear', 'search', '|',
'help'
]
}, // 自定义工具栏,相关配置查看toolbarModes
previewCodeHighlight: true, // 预览 HTML 的代码块高亮,默认开启
emoji: false,
taskList: true, // 任务列表
tocm: true, // Using [TOCM]
tex: false, // 开启科学公式TeX语言支持,默认关闭
flowChart: true, // 开启流程图支持,默认关闭
sequenceDiagram: true, // 开启时序/序列图支持,默认关闭,
dialogLockScreen: false, // 设置弹出层对话框不锁屏,全局通用,默认为true
dialogShowMask: false, // 设置弹出层对话框显示透明遮罩层,全局通用,默认为true
dialogDraggable: false, // 设置弹出层对话框不可拖动,全局通用,默认为true
dialogMaskOpacity: 0.4, // 设置透明遮罩层的透明度,全局通用,默认值为0.1
dialogMaskBgColor: '#000', // 设置透明遮罩层的背景颜色,全局通用,默认为#fff
imageUpload: true,
imageFormats: ['jpg', 'jpeg', 'gif', 'png', 'webp'],
// imageUploadURL: 'http://127.0.0.1:8030/api/files/uploadSingleFile',
// onload: function() {
// // this.fullscreen();
// // this.unwatch();
// // this.watch().fullscreen();
// // this.setMarkdown("#PHP");
// // this.width("100%");
// // this.height(480);
// // this.resize("100%", 640);
// },
// 自定义图片上传函数,需要修改图片上传源码搭配
onCustomImageUpload: function(files) {
// 使用ossUpload工具上传图片
return ossUpload(files, {
folder: 'xxxx/editor_images' // 上传到OSS的文件夹
})
}
}
export {
defaultConfig
}
组件index.vue
相关实现如下
js
<template>
<div class="markdown-editor-box">
<link rel="stylesheet" href="./static/editor.md/css/editormd.min.css">
<div :id="editorId"></div>
</div>
</template>
<script>
import scriptjs from 'scriptjs'
import { defaultConfig } from './editor.md.config'
export default {
name: 'MarkdownEditor',
props: {
editorId: {
type: String,
default: 'markdown-editor'
},
onchange: {
type: Function
},
config: {
type: Object
},
initData: {
type: String
},
initDataDelay: {
type: Number,
default: 0
}
},
data() {
return {
editor: null,
editorLoaded: false
}
},
watch: {
initData: function(newVal) {
if (newVal) {
this.editorLoaded && this.editor.setMarkdown(newVal)
}
}
},
mounted() {
this.initEditor()
},
methods: {
fetchScript(url) {
return new Promise(resolve => {
scriptjs(url, () => {
resolve()
})
})
},
getConfig() {
return { ...defaultConfig, ...this.config }
},
getEditor() {
return this.editor
},
getDoc() {
return this.doc
},
watch() {
return this.editor.watch()
},
unwatch() {
return this.editor.unwatch()
},
previewing() {
return this.editor.previewing()
},
getHTML() {
return this.editor.getHTML()
},
getMarkdown() {
return this.editor.getMarkdown()
},
setMarkdown(markdown) {
return this.editor.setMarkdown(markdown)
},
initEditor() {
(async() => {
await this.fetchScript('./static/editor.md/jquery.min.js')
await this.fetchScript('/static/editor.md/editormd.min.js')
this.$nextTick(() => {
const editor = window.editormd(this.editorId, this.getConfig())
console.log('init editor ', editor)
editor.on('load', () => {
setTimeout(() => {
this.editorLoaded = true
this.initData && editor.setMarkdown(this.initData)
}, this.initDataDelay)
})
this.onchange && editor.on('change', () => {
const html = editor.getPreviewedHTML()
this.onchange({
markdown: editor.getMarkdown(),
html: html,
text: window.$(html).text()
})
})
this.editor = editor
})
})()
}
}
}
</script>
<style scoped lang="scss">
.markdown-editor-box {
width: 100%;
}
</style>
5、页面使用:组件引入直接使用
js
<md-editor ref="MdEditor"></md-editor>
一些常用方法
// 获取编辑器内容
this.$refs.MdEditor.getMarkdown()
// 设置编辑器内容
this.$refs.MdEditor.setMarkdown(res.data.md_content)
// 把editor.md编辑器md格式转成html字符
this.$refs.MdEditor.getHTML()
// 把editor.md编辑器md格式提取纯文本内容
window.$(this.$refs.MdEditor.getHTML()).text()
// 更多查看组件里的methods
阿里云oss自定义上传图片
editor.md.config.js
配置文件增加一个自定义上传函数,上面配置文件可参考
js
// 自定义图片上传函数,需要修改图片上传源码搭配
onCustomImageUpload: function(files) {
// 使用ossUpload工具上传图片
return ossUpload(files, {
folder: 'xxxx/editor_images' // 上传到OSS的文件夹
})
}
修改图片上传源码,文件路径是public\static\editor.md\plugins\image-dialog\image-dialog.js
- 原设计的 是submit型的 button ,来提交表单,表单目标 target 指向了当前的iframe
- 当前上传完成后,服务端返回的内容 到了iframe中。
- 使用iframe的onload事件来拿到服务端返回的结果
修改点:重写方法submitHandler
,注释之前的方法,也可以删除iframe相关html内容
js
fileInput.bind("change", function(event) {
var files = event.target.files;
// ....图片校验 省略...
var submitHandler = function () {
// 调用配置文件中的 自定义图片上传方法
settings.onCustomImageUpload(files).then(ossUrl => {
console.log("🚀 ~ fileInput.bind ~ ossUrl:", ossUrl)
// 填充图片地址到输入框
dialog.find("[data-url]").val(ossUrl);
// 填充图片原名称为图片描述 sourFileName 这个字段是多传进来的
dialog.find("[data-alt]").val(files[0].name);
loading(false);
}).catch(error => {
console.log('uploading errror', error)
alert(error);
})
}
// 原方法
// var submitHandler = function () {
// var uploadIframe = document.getElementById(iframeName);
// uploadIframe.onload = function () {
// loading(false);
// var body = (uploadIframe.contentWindow ? uploadIframe.contentWindow : uploadIframe.contentDocument).document.body;
// var json = (body.innerText) ? body.innerText : ((body.textContent) ? body.textContent : null);
// json = (typeof JSON.parse !== "undefined") ? JSON.parse(json) : eval("(" + json + ")");
// if (!settings.crossDomainUpload) {
// if (json.success === 1) {
// dialog.find("[data-url]").val(json.url);
// }
// else {
// alert(json.message);
// }
// }
// return false;
// };
// };
dialog.find("[type=\"submit\"]").bind("click", submitHandler).trigger("click");
相关参考文档: