tinymce图片上传插件
大约 3 分钟
tinymce 图片上传插件
下载生成器
npm install --global yo generator-tinymce用生成器创建一个插件模板
yo tinymce输入项目名称后一路 next
创建好模板之后会看到有对应的脚本
# 启动项目
yarn start
# 打包插件
yarn build项目目录
.
├── src
│   ├── demo
│   │  ├── html/index.html demo入口
│   │  └── ts/Demo.ts demo配置
│   ├── main/ts
│   │  ├── Main.ts 插件注册入口
│   │  └── Plugin.ts 插件编写
│   └── test 单元测试
├── .editorconfig 编辑器配置
├── .eslintrc.js eslint配置
├── .gitignore git忽略配置
├── CHANGELOG.txt
├── Gruntfile.js
├── LICENSE.txt MIT说明
├── package.json
├── README.md 项目描述文件
├── tsconfig.json ts配置
└── yarn.lock编写组件
申明插件
import { type Editor, type TinyMCE } from "tinymce";
declare const tinymce: TinyMCE;
const setup = (editor: Editor, url: string): void => {
  // 注册工具栏
  editor.ui.registry.addButton("picture", {
    icon: "image",
    tooltip: "上传图片",
    onAction: () => {},
  });
};
export default (): void => {
  tinymce.PluginManager.add("picture", setup);
};上传功能实现
import { type Editor, type TinyMCE } from 'tinymce';
declare const tinymce: TinyMCE;
const openDialog = (editor: Editor) => {
  return editor.windowManager.open({
    title: '上传图片',
    body: {
      type: 'panel',
      items: [
        {
          type: 'dropzone',
          name: 'fileinput'
        }
      ]
    },
    buttons: [
      {
        type: 'cancel',
        text: '关闭'
      },
    ],
    // 监听到有附件上传
    onChange(api) {
      api.block('上传中')
      const files = api.getData().fileinput
      const upload = editor.getParam('upload')
      upload(files, (filePath: string) => {
        editor.execCommand('mceInsertContent', false, `<img src=${filePath} class="" alt=''/>`)
        api.unblock()
        api.close()
      })
    }
  })
}
const setup = (editor: Editor, url: string): void => {
  // 注册工具栏
  editor.ui.registry.addButton('picture', {
    icon: 'image',
    tooltip: '上传图片',
    onAction: () => {
      openDialog(editor)
    }
  });
};
export default (): void => {
  tinymce.PluginManager.add('picture', setup);
};使用
在 plugins 中注册,并在 toolbar 使用,通过 upload 实现上传,将上传成功后的图片路径传入 callback 中
tinymce.init({
  selector: "textarea.tinymce",
  plugins: "code picture",
  toolbar: "picture",
  // 自定义上传方法
  upload: (files: File[], callback: Callback) => {
    // files 上传的附件集合  callback 上传成功的回调
    // ... 自定义上传
    const path = ""; // 上传成功后的文件地址
    callback(path);
  },
});打包
执行打包命令
npm run build打包后会在根目录下生成打包文件
引入项目
将打包后的 picture 文件夹复制到项目本地资源 tinymce\plugins 目录下,然后之间使用即可
