配合 element-ui 实现上传图片/视频到七牛 demo

Chason
2021-03-22 / 0 评论 / 0 点赞 / 971 阅读 / 9,268 字
温馨提示:
本文最后更新于 2021-03-22,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

出处链接:https://github.com/surmon-china/vue-quill-editor/issues/102

<style lang="sass">
.quill-editor
  min-height: 500px

  .ql-container
    min-height: 500px

.ql-snow .ql-editor img
  max-width: 480px

.ql-editor .ql-video
  max-width: 480px
</style>

<template lang="pug">
.the_my_editor_container
  quill-editor(
    v-model="content" 
    ref="myQuillEditor" 
    :options="editorOption" 
  )

  //- 文件上传input 将它隐藏
  el-upload.upload-demo(
    :action="qnLocation" 
    :before-upload='beforeUpload' 
    :data="uploadData" 
    :on-success='upScuccess' 
    ref="upload" 
    style="display:none"
  )
    el-button#imgInput(
      size="small" 
      type="primary" 
      v-loading.fullscreen.lock="fullscreenLoading" 
      element-loading-text="插入中,请稍候"
    ) 点击上传

</template>

<script>
import Vue from 'vue'
import Component from 'vue-class-component'
import Quill from 'quill'

const STATICDOMAIN = 'http://otq0t8ph7.bkt.clouddn.com/' // 图片服务器的域名,展示时使用
const STATVIDEO = 'http://otq0t8ph7.bkt.clouddn.com/'

@Component
export default class Editor extends Vue {
  content = '' // 文章内容
  editorOption = {
    placeholder: '请输入内容',
  }
  addRange = []
  uploadData = {}
  photoUrl = '' // 上传图片地址
  uploadType = '' // 上传的文件类型(图片、视频)
  fullscreenLoading = false

  $refs = {
    myQuillEditor: HTMLInputElement,
    imgInput: HTMLInputElement
  }

  // 上传七牛的actiond地址,http 和 https �不一样
  get qnLocation() {
    return location.protocol === 'http:' ? 'http://upload.qiniu.com' : 'https://up.qbox.me'
  }

  // 图片上传之前调取的函数
  // 这个钩子还支持 promise
  beforeUpload(file) {
    return this.qnUpload(file)
  }

  // 图片上传前获得数据token数据
  qnUpload(file) {
    this.fullscreenLoading = true
    const suffix = file.name.split('.')
    const ext = suffix.splice(suffix.length - 1, 1)[0]
    console.log(this.uploadType)
    if (this.uploadType === 'image') { // 如果是点击插入图片
      // TODO 图片格式/大小限制
      return this.$http('common/get_qiniu_token').then(res => {
        this.uploadData = {
          key: `image/${suffix.join('.')}_${new Date().getTime()}.${ext}`,
          token: res.data
        }
      })
    } else if (this.uploadType === 'video') { // 如果是点击插入视频
      return this.$http('common/get_qiniu_token').then(res => {
        this.uploadData = {
          key: `video/${suffix.join('.')}_${new Date().getTime()}.${ext}`,
          token: res
        }
      })
    }
  }

  // 图片上传成功回调   插入到编辑器中
  upScuccess(e, file, fileList) {
    console.log(e)
    this.fullscreenLoading = false
    let vm = this
    let url = ''
    if (this.uploadType === 'image') { // 获得文件上传后的URL地址
      url = STATICDOMAIN + e.key
    } else if (this.uploadType === 'video') {
      url = STATVIDEO + e.key
    }
    if (url != null && url.length > 0) { // 将文件上传后的URL地址插入到编辑器文本中
      let value = url
      // API: https://segmentfault.com/q/1010000008951906
      // this.$refs.myTextEditor.quillEditor.getSelection();
      // 获取光标位置对象,里面有两个属性,一个是index 还有 一个length,这里要用range.index,即当前光标之前的内容长度,然后再利用 insertEmbed(length, 'image', imageUrl),插入图片即可。
      vm.addRange = vm.$refs.myQuillEditor.quill.getSelection()
      value = value.indexOf('http') !== -1 ? value : 'http:' + value
      vm.$refs.myQuillEditor.quill.insertEmbed(vm.addRange !== null ? vm.addRange.index : 0, vm.uploadType, value, Quill.sources.USER) // 调用编辑器的 insertEmbed 方法,插入URL
    } else {
      this.$message.error(`${vm.uploadType}插入失败`)
    }
    this.$refs['upload'].clearFiles() // 插入成功后清除input的内容
  }

  // 点击图片ICON触发事件
  imgHandler(state) {
    this.addRange = this.$refs.myQuillEditor.quill.getSelection()
    if (state) {
      let fileInput = document.getElementById('imgInput')
      fileInput.click() // 加一个触发事件
    }
    this.uploadType = 'image'
  }

  // 点击视频ICON触发事件
  videoHandler(state) {
    this.addRange = this.$refs.myQuillEditor.quill.getSelection()
    if (state) {
      let fileInput = document.getElementById('imgInput')
      fileInput.click() // 加一个触发事件
    }
    this.uploadType = 'video'
  }

  // 页面加载后执行 为编辑器的图片图标和视频图标绑定点击事件
  mounted() {
    // 为图片ICON绑定事件  getModule 为编辑器的内部属性
    this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('video', this.videoHandler) // 为视频ICON绑定事件
  }
}
</script>

改一下 STATICDOMAIN 变量,换成你自己的七牛配置的域名,
浏览器输入 STATICDOMAIN + key 就能访问你上传成功的图片/视频

这个只是客户端代码,还需要服务器实现一个接口,通过这个接口能获取七牛的 token 。
this.$http('common/get_qiniu_token') 这个方法换成你自己的获取token方法。

改完以上两点,亲测没问题。


其他:https://blog.csdn.net/lyj2018gyq/article/details/82585194

<template>
  <div>
    <quilleditor v-model="content"
                 ref="myTextEditor"
                 :options="editorOption"
                 @change="onChange"
                 >
      <div id="toolbar" slot="toolbar">
        <select class="ql-size">
          <option value="small"></option>
          <!-- Note a missing, thus falsy value, is used to reset to default -->
          <option selected></option>
          <option value="large"></option>
          <option value="huge"></option>
        </select>
        <!-- Add subscript and superscript buttons -->
        <span class="ql-formats"><button class="ql-script" value="sub"></button></span>
        <span class="ql-formats"><button class="ql-script" value="super"></button></span>
        <span class="ql-formats"><button type="button" class="ql-bold"></button></span>
        <span class="ql-formats"><button type="button" class="ql-italic"></button></span>
        <span class="ql-formats"><button type="button" class="ql-blockquote"></button></span>
        <span class="ql-formats"><button type="button" class="ql-list" value="ordered"></button></span>
        <span class="ql-formats"><button type="button" class="ql-list" value="bullet"></button></span>
        <span class="ql-formats"><button type="button" class="ql-link"></button></span>
        <span class="ql-formats">
        <button type="button" @click="imgClick" style="outline:none">
        <svg viewBox="0 0 18 18"> <rect class="ql-stroke" height="10" width="12" x="3" y="4"></rect> <circle
          class="ql-fill" cx="6" cy="7" r="1"></circle> <polyline class="ql-even ql-fill"
                                                                  points="5 12 5 11 7 9 8 10 11 7 13 9 13 12 5 12"></polyline> </svg>
        </button>
      </span>
        <span class="ql-formats"><button type="button" class="ql-video"></button></span>
      </div>
    </quilleditor>
  </div>
</template>
<script>
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
 
  import {quillEditor} from 'vue-quill-editor'
 
  export default {
    name: "v-editor",
    props: {
      value: {
        type: String
      },
      /*上传图片的地址*/
      uploadUrl: {
        type: String,
        default: '/'
      },
      /*上传图片的file控件name*/
      fileName: {
        type: String,
        default: 'file'
      },
      maxUploadSize:{
        type:Number,
        default: 1024 * 1024 * 500
      }
    },
    data() {
      return {
        content: '',
        editorOption: {
          modules: {
            toolbar: '#toolbar'
          }
        },
      }
    },
    methods: {
      onChange() {
        this.$emit('input', this.content)
      },
      /*选择上传图片切换*/
      onFileChange(e) {
        var fileInput = e.target;
        if (fileInput.files.length === 0) {
          return
        }
        this.editor.focus();
        if (fileInput.files[0].size > this.maxUploadSize) {
          this.$alert('图片不能大于500KB', '图片尺寸过大', {
            confirmButtonText: '确定',
            type: 'warning',
          })
        }
        var data = new FormData;
        data.append(this.fileName, fileInput.files[0]);
        this.$http.post(this.uploadUrl, data)
          .then(res => {
            if (res.data) {
              console.log(res.data);
              this.editor.insertEmbed(this.editor.getSelection().index, 'image', res.data)
            }
          })
      },
      /*点击上传图片按钮*/
      imgClick() {
        if (!this.uploadUrl) {
          console.log('no editor uploadUrl');
          return;
        }
        /*内存创建input file*/
        var input = document.createElement('input');
        input.type = 'file';
        input.name = this.fileName;
        input.accept = 'image/jpeg,image/png,image/jpg,image/gif';
        input.onchange = this.onFileChange;
        input.click()
      }
    },
    computed: {
      editor() {
        return this.$refs.myTextEditor.quill
      }
    },
    components: {
      'quilleditor': quillEditor
    },
    mounted() {
      this.content = this.value
    },
    watch: {
      'value'(newVal, oldVal) {
        if (this.editor) {
          if (newVal !== this.content) {
            this.content = newVal
          }
        }
      },
    }
  }
 
</script>

初始编辑器:

image.png

修改后的编辑器:

image.png

去除一些多余的功能,实现图片上传到服务器主要是以下代码:

      /*选择上传图片切换*/
      onFileChange(e) {
        var fileInput = e.target;
        if (fileInput.files.length === 0) {
          return
        }
        this.editor.focus();
        if (fileInput.files[0].size > this.maxUploadSize) {
          this.$alert('图片不能大于500KB', '图片尺寸过大', {
            confirmButtonText: '确定',
            type: 'warning',
          })
        }
        var data = new FormData;
        data.append(this.fileName, fileInput.files[0]);
        this.$http.post(this.uploadUrl, data)
          .then(res => {
            if (res.data) {
              console.log(res.data);
              this.editor.insertEmbed(this.editor.getSelection().index, 'image', res.data)
            }
          })
      },
      /*点击上传图片按钮*/
      imgClick() {
        if (!this.uploadUrl) {
          console.log('no editor uploadUrl');
          return;
        }
        /*内存创建input file*/
        var input = document.createElement('input');
        input.type = 'file';
        input.name = this.fileName;
        input.accept = 'image/jpeg,image/png,image/jpg,image/gif';
        input.onchange = this.onFileChange;
        input.click()
      }

点击上传图片按钮后,先调用imgClick方法,当内容改变时调用onFileChange方法,将图片上传到服务器。服务器路径存放在this.uploadUrl中,通过调用组件时传入。组件调用:

<v-editor  v-model="text" upload-url="/upload/image" fileName="file"/>

属性说明:

属性名说明数据类型默认值
value编辑器的输出结果,可以用v-model双向绑定String
upload-url上传按钮对应的图片上传地址,以项目全局的url配置为前缀String
file-name上传文件的参数名Stringfile
maxUploadSize上传文件的大小限制,单位byteNumber500kb

备注:

默认支持的图片类型:jpg/png/jpeg/gif

测试结果:

image.png

后台数据库:

image.png

0

评论区