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

使用方法

不管vue-quill-editor對(duì)接的是那個(gè)UI框架,還是全部自己寫,其實(shí)使用方法都是一樣的。

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

獲取七牛token上傳

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

// 上傳圖片typescript
import { getQNToken } from '@/assets/api/QiNiu' // 已經(jīng)寫好的請(qǐ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會(huì)緩存token到sessionStorage,發(fā)現(xiàn)沒有重新請(qǐng)求
    const token = sessionStorage.getItem('QNToken') || await getQNToken(***) // 獲取token
    const n = name.replace('.', '_' + new Date().getTime() + '.')   // 重新命名
    const key = prefix ? (prefix + '/' + n) : n // 加上傳過(guò)來(lái)的前綴
    const observable = qiniu.upload(file, key, token, putExtra, config) // 使用SDK方式發(fā)起請(qǐng)求
    // next 是一個(gè)回調(diào)函數(shù)
    observable.subscribe(next, (error) => {
      reject(error)
    }, (complete) => {
      resolve(complete)
    })
  })
}

export default QNUpload

base64 to blob二進(jìn)制

/**
 * base64  to blob二進(jìn)制
 * @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
  // 設(shè)置提示圖尺寸
  @Prop({ default: 200 }) readonly width!: number
  @Prop({ default: 200 }) readonly height!: number
  // 組件層控制上傳類型,默認(rèn)是圖片
  @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
      // 大小驗(yàn)證
      if (/image/g.test(file.type) && file.size / 1024 > size) {
        this.$Message.info({ content: file.name + '大小不能超過(guò)' + 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) => {
          // 上傳進(jìn)度
          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",就可以選中多個(gè)文件上傳

<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: {
          // 點(diǎn)擊 image會(huì)調(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', () => {
      // 獲取當(dāng)前鼠標(biāo)位置
      this.addRange = Quill.getSelection()
      // 觸發(fā)上傳,可以單獨(dú)寫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ā)擴(kuò)展還是很好開發(fā)的。
一直有個(gè)疑問(wèn)就是:quill-editor自己整了一套數(shù)據(jù)接口delta,通過(guò)quill.getContents()獲取到delta,這個(gè)delta怎么展示在沒有引入這個(gè)包的界面上?
現(xiàn)在我的辦法是:直接獲取container的innerHTML
不知還有更好的辦法沒?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容