vue-quill-editor 上傳圖片至七牛

使用方法

不管vue-quill-editor對接的是那個UI框架念逞,還是全部自己寫贩耐,其實使用方法都是一樣的。

  • 首先都是先能將文件上傳至七牛
  • 然后針對vue-quill-editor開發(fā)handlers方法,觸發(fā)上傳功能载慈,拿到回調(diào)值徽千,insert進入富文本苫费。

獲取七牛token上傳

region: 上傳區(qū)域,可以設置為undefined
具體參數(shù)解釋說明 參考文檔双抽,原文文檔寫得比較詳細百框。

// 上傳圖片typescript
import { getQNToken } from '@/assets/api/QiNiu' // 已經(jīng)寫好的請求token接口
const qiniu = require('qiniu-js')

const QNUpload = (file: any, prefix: string, name: string, next) => {
  return new Promise(async (resolve, reject) => {
    const putExtra = {
      fname: name,
      params: {},
      mimeType: null
    }
    const config = {
      useCdnDomain: false // 是否使用 cdn 加速域名
    }
    // 接口getQNToken會緩存token到sessionStorage,發(fā)現(xiàn)沒有重新請求
    const token = sessionStorage.getItem('QNToken') || await getQNToken(***) // 獲取token
    const n = name.replace('.', '_' + new Date().getTime() + '.')   // 重新命名
    const key = prefix ? (prefix + '/' + n) : n // 加上傳過來的前綴
    const observable = qiniu.upload(file, key, token, putExtra, config) // 使用SDK方式發(fā)起請求
    // next 是一個回調(diào)函數(shù)
    observable.subscribe(next, (error) => {
      reject(error)
    }, (complete) => {
      resolve(complete)
    })
  })
}

export default QNUpload

base64 to blob二進制

/**
 * base64  to blob二進制
 * @param {*} dataURI:string
 */
const dataURItoBlob = (dataURI) => {
  const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
  const byteString = atob(dataURI.split(',')[1])
  const arrayBuffer = new ArrayBuffer(byteString.length)
  const intArray = new Uint8Array(arrayBuffer)

  for (let i = 0; i < byteString.length; i++) {
    intArray[i] = byteString.charCodeAt(i)
  }
  return new Blob([intArray], { type: mimeString })
}

上傳文件組件

<template>
  <div class="upload">
    <Icon type="md-add" />
    <span v-show="width>0">{{width}} * {{height}}</span>
    <input type="file" @change="uploadFile" :accept="mimeType"/>
    <div class="progress" v-show="percent && percent !== 100">
      <Progress :percent="percent" hide-info />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Emit, Prop } from 'vue-property-decorator'
import { dataURItoBlob } from '@/assets/common'
import QNUpload from '@/assets/api/upload'

interface QNReceive {
  type: string,
  data: object
}

@Component
export default class Upload extends Vue {
  // 上傳路徑前綴
  @Prop(String) readonly prefix!: string
  @Prop(String) readonly field!: string
  // 控制文件上傳大小
  @Prop({ default: 1024 }) readonly size!: number
  // 設置提示圖尺寸
  @Prop({ default: 200 }) readonly width!: number
  @Prop({ default: 200 }) readonly height!: number
  // 組件層控制上傳類型牍汹,默認是圖片
  @Prop({ default: 'image/png, image/jpeg, image/gif, image/jpg' }) readonly mimeType!: string
  // 已上傳圖片大小占比
  percent:number = 0

  @Emit()
  uploadFile (e) {
    const files = e.target.files
    if (!files.length) return
    let keys: Array<any> = []
    for (let i = 0, len = files.length; i < len; i++) {
      const file = files[i]
      const size = this.size
      // 大小驗證
      if (/image/g.test(file.type) && file.size / 1024 > size) {
        this.$Message.info({ content: file.name + '大小不能超過' + size + 'KB', duration: 5 })
        continue
      }
      // 讀取文件轉(zhuǎn)blob
      const reader = new FileReader()
      reader.addEventListener('load', (data: any) => {
        const dataURI = data.target.result
        const blob = dataURItoBlob(dataURI)
        const name = file.name
        const prefix = this.prefix
        // 調(diào)取上傳方法
        QNUpload(blob, prefix, name, (next) => {
          // 上傳進度
          this.percent = next.total.percent
        }).then((data) => {
          this.$emit('completeUpload', Object.assign(data, { field: this.field }))
        }).catch(error => {
          console.log(error)
        })
      })
      reader.readAsDataURL(file)
    }
  }
}
</script>

<style lang="scss">
.upload {
  width: 100%;
  height: 80px;
  position: relative;
  border: 1px dashed #cccccc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
  }
  i {
    font-size: 40px;
    cursor: pointer;
  }
  .progress {
    position: absolute;
    bottom: 2px;
    left: 0;
    width: 100%;
    height: 20px;
  }
  span {
    position: absolute;
    bottom: 0;
    left: 0;
    display: block;
    width: 100%;
    height: 20px;
    line-height: 20px;
    color: $grayColor;
    text-align: center;
    font-weight: bold;
  }
}
</style>

vue-quill-editor富文本添加上傳圖片

使用組件的方式加載富文本琅翻,配置toolbar,添加handlers處理方法柑贞。最后完成插入圖片
這里只配置了一張一張圖片上傳方椎,稍微改一下,添加multiple="true"钧嘶,就可以選中多個文件上傳

<template>
  <div>
    <quill-editor style="height: 800px;" ref="myQuillEditor" v-model="Qcontent" :options="editorOption"></quill-editor>
    <v-upload ref="upload" v-show="false" @completeUpload="getCompleteUpload" prefix="goodsDetail"></v-upload>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Emit, PropSync, Prop, Watch } from 'vue-property-decorator'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import VUpload from '@/components/Upload.vue'

@Component({
  components: {
    quillEditor,
    VUpload
  }
})
export default class QuillEditor extends Vue {
  @PropSync('content', { default: '' }) readonly Qcontent?: string
  @Prop({ default: false }) readonly sendContent?: Boolean

  @Watch('sendContent')
  onSendContentChanged(val: boolean, oldVal: boolean) {
    if (val) {
      this.$emit('getContent', this.Quill.container.innerHTML)
    }
  }
  QNHost = ****
  Quill:any = ''
  addRange: any = ''
  uploadType = ''
  editorOption = {
    modules: {
      toolbar: {
        container: [
          ['bold', 'italic', 'underline'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean'],
          // 新增image棠众,使用自帶的icon,添加新的handlers
          ['image']
        ],
        handlers: {
          // 點擊 image會調(diào)取方法imgHandler
          image: this.imgHandler
        }
      }
    }
  }

  mounted () {
    this.imgHandler()
  }

  @Emit()
  imgHandler () {
    const Quill: any = (this.$refs.myQuillEditor as Vue & {quill: () => any}).quill
    this.Quill = Quill
    const toolbar = Quill.getModule('toolbar')
    const upload: any = this.$refs.upload

    toolbar.addHandler('image', () => {
      // 獲取當前鼠標位置
      this.addRange = Quill.getSelection()
      // 觸發(fā)上傳有决,可以單獨寫input直接觸發(fā)闸拿,這里使用封裝的組件
      upload.$el.getElementsByTagName('input')[0].click()
    })
  }

  @Emit()
  getCompleteUpload (data) {
    const index = this.addRange.index || 0
    // 上傳成功拿到返回值,插入富文本
    this.Quill.insertEmbed(index, 'image', this.QNHost + data.key)
  }
}
</script>

總結(jié)

quill-editor 開發(fā)擴展還是很好開發(fā)的书幕。
一直有個疑問就是:quill-editor自己整了一套數(shù)據(jù)接口delta新荤,通過quill.getContents()獲取到delta,這個delta怎么展示在沒有引入這個包的界面上台汇?
現(xiàn)在我的辦法是:直接獲取container的innerHTML
不知還有更好的辦法沒苛骨?

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末篱瞎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子痒芝,更是在濱河造成了極大的恐慌俐筋,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件严衬,死亡現(xiàn)場離奇詭異澄者,居然都是意外死亡,警方通過查閱死者的電腦和手機请琳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門粱挡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人俄精,你說我怎么就攤上這事抱怔。” “怎么了嘀倒?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵屈留,是天一觀的道長。 經(jīng)常有香客問我测蘑,道長灌危,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任碳胳,我火速辦了婚禮勇蝙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘挨约。我一直安慰自己味混,他們只是感情好,可當我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布诫惭。 她就那樣靜靜地躺著翁锡,像睡著了一般。 火紅的嫁衣襯著肌膚如雪夕土。 梳的紋絲不亂的頭發(fā)上馆衔,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天,我揣著相機與錄音怨绣,去河邊找鬼角溃。 笑死,一個胖子當著我的面吹牛篮撑,可吹牛的內(nèi)容都是我干的减细。 我是一名探鬼主播,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼赢笨,長吁一口氣:“原來是場噩夢啊……” “哼未蝌!你這毒婦竟也來了驮吱?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤树埠,失蹤者是張志新(化名)和其女友劉穎糠馆,沒想到半個月后嘶伟,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體怎憋,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年九昧,在試婚紗的時候發(fā)現(xiàn)自己被綠了绊袋。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡铸鹰,死狀恐怖癌别,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蹋笼,我是刑警寧澤展姐,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站剖毯,受9級特大地震影響圾笨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜逊谋,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一擂达、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧胶滋,春花似錦板鬓、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至部宿,卻和暖如春唤蔗,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背窟赏。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工妓柜, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人涯穷。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓棍掐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親拷况。 傳聞我的和親對象是個殘疾皇子作煌,可洞房花燭夜當晚...
    茶點故事閱讀 45,515評論 2 359

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