如何重写 toast-ui/editor 完成阿里云oss图片上传

2024年1月22日
1089 次阅读
admin

1.toast-ui/editor介绍

TOAST UI Editor 是一款 GFM Markdown 所见即所得编辑器,提供 Markdown 和 Wysiwyg 两种模式,对于技术人员来说可以非常方便的做出自己的markdown的页面。那么我们在做富文本编辑的时候。我们该如何较为方便的上传自己的图片文件呢?


2.图片上传

在toast-ui/editor中。我们如果不去重写图片上传的函数的话。会让我们以后写(水)文章非常不方便。在这里我就去重写markdown的图片上传的函数。在TOAST UI Editor这个包中。作者非常贴心的为我们留下了重写的HOOK。addImageBlobHook


3.如何重写图片上传。实现自定义上传位置。

下面我就拿我自己的代码举例。利用python搭配这个包实现粘贴图片自动上传到阿里云 后端接口代码

class aliOssBlogMarkdownimg():
    def __init__(self):
        access_key_id = os.getenv('ACCESS_KEY_ID')
        access_key_secret = os.getenv('ACCESS_KEY_SECRET')


        # 填写自己的 Bucket 名称和上传地址
        self.bucket_name = ''
        self.upload_path = ''

        # 创建 OSS 链接
        auth = oss2.Auth(access_key_id, access_key_secret)
        self.bucket = oss2.Bucket(auth, 'http://oss-cn-shanghai.aliyuncs.com', self.bucket_name)


    def upload_bitsfileMarkdownimg(self,bitsfile,current_blogimgconunt):
        self.bucket.put_object(f'{self.upload_path}{current_blogimgconunt}.jpg', bitsfile)

        # 二进制上传博客图片
    async def Binaryfileuploadmarkdownimg(self,bitsfile,current_blogimgconunt):
        await asyncio.to_thread(self.upload_bitsfileMarkdownimg,bitsfile,current_blogimgconunt)
        image_url = f"http://{self.bucket_name}.oss-cn-shanghai.aliyuncs.com/{self.upload_path}{current_blogimgconunt}.jpg"
        return image_url

##定义一个post接口
@AdminApi.post('/markdown/uploadimg/')
async def markdown_img_upload(file: UploadFile = File(...), token: str = Depends(Adminoauth2_scheme)):
    x = datetime.datetime.now().strftime("%Y-%m-%d,%H:%M:%S")
    waitmarkdownimg = await file.read()
    image_url = await aliOssBlogMarkdownimg().Binaryfileuploadmarkdownimg(bitsfile=waitmarkdownimg, current_blogimgconunt=x)
    return {"code": 20000, "msg": "图片上传成功", "file": file.filename, "url": image_url}

那么这个简单的后端接口就写好了。我使用的是阿里云的二进制上传。这样子就不用读取文件路径了。


4.前端代码

这里注意编辑的是toast-ui/editor包的index.js函数

<template>
  <div :id="id" />
</template>

<script>
// deps for editor
// import 'codemirror/lib/codemirror.css' // codemirror
// import 'tui-editor/dist/tui-editor.css' // editor ui
// import 'tui-editor/dist/tui-editor-contents.css' // editor content

import 'codemirror/lib/codemirror.css' // Editor's Dependency Style
import '@toast-ui/editor/dist/toastui-editor.css' // Editor's Style
// import Editor from 'tui-editor'
import Editor from '@toast-ui/editor'
import defaultOptions from './default-options'
import { uploadImg } from '@/api/admin/upload'

export default {
  name: 'MarkdownEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      required: false,
      default() {
        return 'markdown-editor-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    options: {
      type: Object,
      default() {
        return defaultOptions
      }
    },
    mode: {
      type: String,
      default: 'markdown'
    },
    height: {
      type: String,
      required: false,
      default: '300px'
    },
    language: {
      type: String,
      required: false,
      default: 'en_US' // https://github.com/nhnent/tui.editor/tree/master/src/js/langs
    }
  },
  data() {
    return {
      editor: null
    }
  },
  computed: {
    editorOptions() {
      const options = Object.assign({}, defaultOptions, this.options)
      options.initialEditType = this.mode
      options.height = this.height
      options.language = this.language
      return options
    }
  },
  watch: {
    value(newValue, preValue) {
      if (newValue !== preValue && newValue !== this.editor.getMarkdown()) {
        this.editor.setMarkdown(newValue)
      }
    },
    language(val) {
      this.destroyEditor()
      this.initEditor()
    },
    height(newValue) {
      this.editor.height(newValue)
    },
    mode(newValue) {
      this.editor.changeMode(newValue)
    }
  },
  mounted() {
    this.initEditor()
  },
  destroyed() {
    this.destroyEditor()
  },
  methods: {
    initEditor() {
      this.editor = new Editor({
        el: document.getElementById(this.id),
        ...this.editorOptions
      })
      if (this.value) {
        this.editor.setMarkdown(this.value)
      }
      this.editor.on('change', () => {
        this.$emit('input', this.editor.getMarkdown())
      })
      //添加这个函数调用
      this.uploadImg()
    },
    destroyEditor() {
      if (!this.editor) return
      this.editor.off('change')
      this.editor.remove()
    },
    setValue(value) {
      this.editor.setMarkdown(value)
    },
    getValue() {
      return this.editor.getMarkdown()
    },
    setHtml(value) {
      this.editor.setHtml(value)
    },
    getHtml() {
      return this.editor.getHtml()
    },
    //在这里我们重写addImageBlobHook。
    uploadImg() {
      this.editor.removeHook('addImageBlobHook')
      this.editor.on('addImageBlobHook', (_file, cb) => {
        const file = new FormData()
        file.append('file', _file)
        //uploadImg是一个接口函数。是后端代码中的接口地址
        const result = uploadImg(file)
        result.then(({ code, msg, url }) => {
          if (code === 20000) {
            this.$message.success(msg)
            cb(url, file.name)
          }
        })
      })
    }
  }
}
</script>

当上面的工作完成后。我们重新打卡markdown的编辑器。粘贴图片就可以看到图片被存入到你想存入的地址了。且可以被正常显示出来。


5.注意事项

如果你使用的和我一样是阿里云oss或者其他的oss。一定要注意观察oss的上传规则。比如是否有空格。是否有中文的路径。否则当你粘贴到编辑器后。反而不会显示出来

评论区

0 / 500
* 为必填项