魔改 Simditor 編輯器,增強(qiáng)自定義上傳

2018-07-13 今天得空,就來(lái)梳理下這個(gè)東東缀蹄。

這個(gè)現(xiàn)場(chǎng)情況是這樣的:

  • 需要將附件通過(guò)web直傳到Aliyun-OSS
  • web-client upload file -> Aliyun-OSS Server -> response file-token -> web-client upload file-token to private-server -> response source-url -> web-client preview
  • 這個(gè)需求,就必須得自行編寫個(gè)Simditor-upload插件了

  • Simditor-upload插件 : simditor-http-upload.js
  • Simditor配置:simditor.config.js

simditor-http-upload.js

/* eslint-disable */
import $ from 'jquery'
import Simditor from 'simditor'

const inputAttribute = {
  accept: 'image/gif,image/jpeg,image/jpg,image/png,image/svg',
  multiple: false
}

class HttpUploadButton extends Simditor.Button {
  constructor(...args) {
    super(...args)
    this.i18n = {
      'zh-CN': {
        httpupload: '上傳文件'
      },
      'en-US': {
        httpupload: 'upload file'
      }
    }
    this.init()
  }

  init() {
    const {
      httpUpload
    } = this.editor.opts
    if (!httpUpload && !httpUpload.bindUpload) {
      throw new Error('upload httpUpload must config httpUpload.')
    }

    this.input = $('<input />', {
      type: 'file',
      class: 'plugin-http-upload',
      accept: inputAttribute.accept,
      multiple: inputAttribute.multiple,
      style: 'position:absolute;top:0;right:0;opacity:0;filter:alpha(opacity=0);cursor:pointer;'
    }).prependTo(this.editor.el)

    this.editor.el.on('click mouseup', '.toolbar-item-httpupload', (e) => {
      if (!this.editor.selection.range()) {
        console.warn('current not is focus.')
        httpUpload.error('請(qǐng)點(diǎn)擊編輯區(qū)域膘婶,然后上傳')
        return undefined
      }
      this.$rootNodes = this.editor.selection.blockNodes()
      this.editor.selection.save()
      this.input.trigger('click')
      e.stopPropagation()
    })
    this.editor.el.on('change', '.plugin-http-upload', () => {
      httpUpload.bindUpload(this.input, (data) => {
        this.input.val('')
        if (['', null, undefined].indexOf(data) === -1) {
          let $insert = ''
          if (Array.isArray(data)) {
            const imgs = data.map(link => `<img src="${link}">`)
            $insert = $(`${imgs.join('')}`)
          } else if (typeof data === 'string') {
            $insert = /^http/.test(data) ? $(`<img src="${data}">`) : $(`<span>${data}</span>`)
          }
          this.editor.selection.restore()
          this.editor.selection.insertNode($insert)
        }
        this.editor.trigger('valuechanged')
        this.editor.trigger('selectionchanged')
      })
    })
  }
}
HttpUploadButton.prototype.type = 'ul.simditor-uploadfile'
HttpUploadButton.prototype.name = 'httpupload'
// HttpUploadButton.prototype.icon = 'upload'
HttpUploadButton.prototype.icon = 'picture-o'

export default (option = {}) => {
  Object.assign(inputAttribute, option)
  Simditor.Toolbar.addButton(HttpUploadButton)
}


simditor.config.js

/* eslint-disable */
import { Toast } from 'mint-ui'
import Simditor from 'simditor'
import SimditorHttpUpload from './simditor-http-upload'

class SimditorConfig {
  constructor(context, el) {
    // 組件環(huán)境
    this.context = context
    // 編輯器實(shí)例
    this.instance = this.init(el)
  }

  init(el) {
    SimditorHttpUpload({
      accept: 'image/jpeg,image/jpg,image/png'
    })
    return new Simditor({
      textarea: document.querySelector(el),
      toolbar: ['bold', 'italic', '|', 'httpupload'],
      placeholder: '請(qǐng)輸入正文',
      toolbarFloat: true,
      toolbarFloatOffset: 0,
      pasteImage: false,
      httpUpload: {
        bindUpload: this.bindAttachUpload.bind(this),
        error: (err) => {
          console.warn(`httpUpload Error: ${err}`)
          Toast(err)
        }
      }
    })
  }

  // 綁定上傳
  bindAttachUpload(uploadInput, callback) {
    if (callback) {
      this.handleUpload(uploadInput[0].files)
        .then((list) => {
          callback(list)
        })
        .catch(err => console.warn(err))
    }
  }

  // 銷毀
  destroy() {
    this.instance.destroy()
  }

  // 真實(shí)上傳
  handleUpload(files) {
    return new Promise((resolve, reject) => {
      if (this.context.httpUpload) {
        this.context.httpUpload({
          files,
          success: (list) => {
            resolve(list)
          }
        })
      } else {
        reject('not found methods: httpUpload.')
        throw new Error(`${this.context} not found methods: httpUpload.`)
      }
    })
  }
}

export default SimditorConfig


使用

Index.vue

import SimditorConfig from './simditor.config'

export default {
  name: 'RichText',
  mounted() {
    this.$nextTick(() => {
      this.editor = new SimditorConfig(this, '#editor')
    })
  },
  methods: {
    // 三方上傳
    httpUpload({ files, success } = {}) {
      if (!this.oss) {
        this.$topTips('關(guān)鍵信息初始化失敗缺前,請(qǐng)刷新重試')
        return undefined
      }

      const upload = (fileList) => {
        fileList.forEach((file) => {
          file.progress = (p) => {
            this.progress = p * 100
          }
        })
        this.handleUploadFileMultiple({ files: fileList })
          .then((response) => {
            const imgs = response.map(obj => obj.url)
            success(imgs)
          })
          .catch((err) => {
            console.error(err)
          })
      }
      upload([...files])
    }
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市悬襟,隨后出現(xiàn)的幾起案子衅码,更是在濱河造成了極大的恐慌,老刑警劉巖古胆,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件肆良,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡逸绎,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門夭谤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)棺牧,“玉大人,你說(shuō)我怎么就攤上這事朗儒〖粘耍” “怎么了参淹?”我有些...
    開封第一講書人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)乏悄。 經(jīng)常有香客問我浙值,道長(zhǎng),這世上最難降的妖魔是什么檩小? 我笑而不...
    開封第一講書人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任开呐,我火速辦了婚禮,結(jié)果婚禮上规求,老公的妹妹穿的比我還像新娘筐付。我一直安慰自己,他們只是感情好阻肿,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開白布瓦戚。 她就那樣靜靜地躺著,像睡著了一般丛塌。 火紅的嫁衣襯著肌膚如雪较解。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,541評(píng)論 1 305
  • 那天赴邻,我揣著相機(jī)與錄音印衔,去河邊找鬼。 笑死乍楚,一個(gè)胖子當(dāng)著我的面吹牛当编,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播徒溪,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼忿偷,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了臊泌?” 一聲冷哼從身側(cè)響起鲤桥,我...
    開封第一講書人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎渠概,沒想到半個(gè)月后茶凳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡播揪,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年贮喧,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片猪狈。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡箱沦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出雇庙,到底是詐尸還是另有隱情谓形,我是刑警寧澤灶伊,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站寒跳,受9級(jí)特大地震影響聘萨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜童太,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一米辐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧康愤,春花似錦儡循、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至检激,卻和暖如春肴捉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背叔收。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工齿穗, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人饺律。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓窃页,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親复濒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子脖卖,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容