看官方文档要求 @WangEditor/editor
版本 >=5.1.16
下载上传附件的插件
yarn add @wangeditor/plugin-upload-attachment
首先要注册到编辑器,如果把下面的代码写在WangEditor的组件里出现第一次使用编辑没问题,但是第二次编辑会报错的问题,那么可能是多次注册引起的,将下面的注册代码写在main.ts文件里。
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'// 注册。要在创建编辑器之前注册,且只能注册一次,不可重复注册。
Boot.registerModule(attachmentModule)
然后在
import { IToolbarConfig, IEditorConfig } from "@wangeditor/editor";
const editorConfig: Partial<IEditorConfig> = {// 在编辑器中,点击选中“附件”节点时,要弹出的菜单hoverbarKeys: {attachment: {menuKeys: ['downloadAttachment'], // “下载附件”菜单},},MENU_CONF: {
/*** @description 附件自定义上传* @param file 上传的文件* @param insertFn 上传成功后的回调函数(插入到富文本编辑器中)* */uploadAttachment: {customUpload(file: File, insertFn: Function) {let formData = new FormData();formData.append("files", file);upload(formData).then(res => { //upload是上传附件接口if (res.success) {console.log(res.data); //defaultconfigUrl是接口地址 insertFn(`${res.data[0].fileName}`, defaultconfigUrl + res.data[0]!.fileUrl);}});}}
};//工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {// 插入哪些菜单insertKeys: {index: 0, // 自定义插入的位置keys: ['uploadAttachment'], // “上传附件”菜单},}
最后效果