Vue中使用editor.md(2):添加拖拽图片上传功能

0. 背景

在对editor.md简单使用后,希望添加图片拖拽或粘贴上传的功能。
简单使用参考:Vue中使用editor.md(1):简单使用

1. 实现

1.1 添加粘贴监听

在这里插入图片描述

// 使用axios
import axios from '@/api/index'

function initPasteDragImg (Editor) {
    
    
  console.log('init paste drag image')
  const doc = document.getElementById(Editor.id)
  doc.addEventListener('paste', function (event) {
    
    
    const items = (event.clipboardData || window.clipboardData).items
    let file = null
    console.log(items)
    console.log(items.length)
    if (items && items.length) {
    
    
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
    
    
        if (items[i].type.indexOf('image') !== -1) {
    
    
          file = items[i].getAsFile()
          break
        }
      }
    } else {
    
    
      console.log('当前浏览器不支持')
      return
    }
    if (!file) {
    
    
      console.log('粘贴内容非图片')
      return
    }
    uploadImg(file, Editor)
  })
  const dashboard = document.getElementById(Editor.id)
  dashboard.addEventListener('dragover', function (e) {
    
    
    e.preventDefault()
    e.stopPropagation()
  })
  dashboard.addEventListener('dragenter', function (e) {
    
    
    e.preventDefault()
    e.stopPropagation()
  })
  dashboard.addEventListener('drop', function (e) {
    
    
    e.preventDefault()
    e.stopPropagation()
    const files = this.files || e.dataTransfer.files
    uploadImg(files[0], Editor)
  })
}

async function uploadImg (file, Editor) {
    
    
  const formData = new FormData()
  const fileName = new Date().getTime() + '.' + file.name.split('.').pop()
  formData.append('file', file, fileName)
  /* $.ajax({
    url: Editor.settings.imageUploadURL,
    type: 'post',
    data: formData,
    processData: false,
    contentType: false,
    dataType: 'json',
    success: function (msg) {
      console.log(msg)
      const success = msg.success
      if (success == 1) {
        const url = msg.url
        if (/\.(png|jpg|jpeg|gif|bmp|ico)$/.test(url)) {
          Editor.insertValue('![](' + msg.url + ')')
        } else {
          Editor.insertValue('[下载附件](' + msg.url + ')')
        }
      } else {
        console.log(msg)
        alert('上传失败')
      }
    }
  }) */
  // 向服务器发送请求
  try {
    
    
    const res = await axios.common.files.uploadSingleFile(file)
    console.log(res)
    if (res.data.errCode === 0) {
    
    
      const url = res.data.data
      if (/\.(png|jpg|jpeg|gif|bmp|ico)$/.test(url)) {
    
    
        Editor.insertValue('![](' + res.data.data + ')')
      } else {
    
    
        Editor.insertValue('[下载附件](' + res.data.data + ')')
      }
    } else {
    
    
      alert('上传失败')
    }
  } catch (e) {
    
    
    console.log(e.message)
  }
}
export {
    
    
  initPasteDragImg
}

1.2 引入粘贴功能

在这里插入图片描述

<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 '@/config/MarkdownConfig'
import {
      
       initPasteDragImg } from '@/config/uploadImg'

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
    }
  },
  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-1.10.2.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(() => {
      
      
              // 拖拽上传图片
              initPasteDragImg(editor)
              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
        })
      })()
    }
  },
  mounted () {
      
      
    this.initEditor()
  },
  watch: {
      
      
    initData: function (newVal) {
      
      
      if (newVal) {
      
      
        this.editorLoaded && this.editor.setMarkdown(newVal)
      }
    }
  }
}
</script>

<style scoped lang="less">

</style>

2. 测试

在这里插入图片描述

x. 参考

  1. editorMd插件的使用总结(包括开启图片上传及拖拉粘贴上传图片)
  2. markdown编辑器之editormd使用整合

猜你喜欢

转载自blog.csdn.net/ice_bear221/article/details/131181203