Toast UI Editor 实现图片粘贴上传到七牛云

Toast UI Editor介绍

  • 一款支持Markdown、WYSIWYG模式的编辑器
  • Github

实现步骤

0. 准备工作
npm install @toast-ui/editor
npm install @toast-ui/editor-plugin-color-syntax
npm install @toast-ui/editor-plugin-code-syntax-highlight
npm install @toast-ui/editor-plugin-chart
npm install @toast-ui/editor-plugin-uml
npm install @toast-ui/editor-plugin-table-merged-cell
1. 去除默认的addImageBlobHook监听事件

Toast UI Editor支持三种图片上传方式:弹窗、拖拽、截屏粘贴。查看文档并测试可知,三种上传方式最终都会被addImageBlobHook监听,并处理为Base64格式的图片。
所以,第一步,我们要去除默认的addImageBlobHook监听事件

  • 此处为默认的addImageBlobHook监听事件,位于src/js/importManager.js中
 /**
   * Initialize default image importer
   * @private
   */
  _initDefaultImageImporter() {
    this.eventManager.listen('addImageBlobHook', (blob, callback) => {
      const reader = new FileReader();

      reader.onload = event => {
        callback(event.target.result);
      };

      reader.readAsDataURL(blob);
    });
  }
  • eventManager.js中提供了删除监听事件的函数removeEventHandler(typeStr, handler)
  /**
   * Remove event handler from given event type
   * @param {string} typeStr Event type name
   * @param {function} [handler] - registered event handler
   */
  removeEventHandler(typeStr, handler) {
    const { type, namespace } = this._getTypeInfo(typeStr);

    if (type && handler) {
      this._removeEventHandlerWithHandler(type, handler);
    } else if (type && !namespace) {
      // dont use dot notation cuz eslint
      this.events.delete(type);
    } else if (!type && namespace) {
      this.events.forEach((eventHandlers, eventType) => {
        this._removeEventHandlerWithTypeInfo(eventType, namespace);
      });
    } else if (type && namespace) {
      this._removeEventHandlerWithTypeInfo(type, namespace);
    }
  }
  • 删除监听事件
// 删除默认监听事件
this.editor.eventManager.removeEventHandler('addImageBlobHook')
2. 添加自定义的addImageBlobHook监听事件
    // 添加自定义监听事件
    this.editor.eventManager.listen('addImageBlobHook', (blob, callback) => {
      // 此处填写自己的上传逻辑,url为上传后的图片地址
      this.upload(blob, url => {
        callback(url)
      })
    })
3. 实现自己的上传逻辑

实现文件上传

4. 最终结果

完美解决三种方式(Popup、Drag、Screenshot)按照自己的上传逻辑进行图片上传

完整源码

  • Toast UI Editor 版本
    "@toast-ui/editor": "^2.1.2"

  • 基于vue的源码示例

<template>
  <div ref="toastUIEditor" />
</template>

<script>
import 'codemirror/lib/codemirror.css'
import '@toast-ui/editor/dist/toastui-editor.css'
import 'tui-color-picker/dist/tui-color-picker.css'

import Editor from '@toast-ui/editor'
import colorSyntax from '@toast-ui/editor-plugin-color-syntax'

export default {
  name: 'Markdown',
  data() {
    return {
      editor: null
    }
  },
  mounted() {
    const options = {
      el: this.$refs.toastUIEditor,
      previewStyle: 'vertical',
      height: '500px',
      initialEditType: 'markdown',
      initialValue: 'Select some text and choose a color from the toolbar.',
      plugins: [colorSyntax]
    }
    this.editor = new Editor(options)
    // 删除默认监听事件
    this.editor.eventManager.removeEventHandler('addImageBlobHook')
    // 添加自定义监听事件
    this.editor.eventManager.listen('addImageBlobHook', (blob, callback) => {
      // 此处填写自己的上传逻辑,url为上传后的图片地址
      this.upload(blob, url => {
        callback(url)
      })
    })
  },
  methods: {
    /**
     * 上传至服务器
     */
    upload(file, callback) {
      const formData = new FormData()
      formData.append('file', file)
      const ajax = new XMLHttpRequest()
      ajax.open('POST', 'http://localhost:9100/qiniu/upload', true)
      ajax.send(formData)
      ajax.onreadystatechange = function() {
        if (ajax.readyState === 4) {
          if ((ajax.status >= 200 && ajax.status < 300) || ajax.status === 304) {
            console.log('上传成功')
            const obj = JSON.parse(ajax.responseText)
            callback(obj.result)
          }
        }
      }
    }
  }
}
</script>

Vue Vant-UIVue.js的一个移动端UI组件库,是一个轻量级的、高效的组件库,非常适合用于移动端前端开发。其中,Van-Uploader是Vant-UI的上传文件组件,允许用户将文件上传到服务器或第三方存储库。 在实现头像图片上传时,我们可以采用如下步骤: 1. 首先需要安装Vant-UI组件库。可以通过npm命令进行安装,输入如下代码:npm install vant --save 2. 在Vue项目中引入Vant-UI组件库。在main.js文件中写入如下代码:import Vant from 'vant' import 'vant/lib/vant-css/index.css' Vue.use(Vant) 3. 在需要使用上传头像的组件中引入Van-Uploader组件,并编写如下代码: <template> <van-uploader :show-upload="false" :before-read="beforeRead" :after-read="afterRead" > <van-icon name="photograph" /> </van-uploader> </template> <script> export default { data() { return { file: '' } }, methods: { beforeRead(file) { if (file.type !== 'image/jpeg' && file.type !== 'image/png') { this.$toast('请上传 JPG/PNG 格式的图片'); return false; } if (file.size > 500 * 1024) { this.$toast('图片大小不能超过 500KB'); return false; } }, afterRead(file) { this.file = URL.createObjectURL(file.file); } } } </script> 4. 上面的代码中,我们主要使用了Van-Uploader组件的before-read和after-read两个事件回调函数。before-read为上传文件之前的校验函数,例如判断文件类型和文件大小是否符合要求,这里我们限制了文件类型为JPG/PNG并且大小不能超过500KB。after-read则表示读取文件后的回调函数,我们将上传的文件读取为本地链接并保存到file属性中,以便进行后续处理。 5. 最后,将file属性传递给后端进行处理,例如将该链接保存到服务器或者上传到第三方存储库中。 总之,使用Van-Uploader组件可以轻松实现头像图片上传功能,同时也可以根据需求进行个性化的定制和扩展,是一个非常实用且易于使用的组件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值