vue-quill-editor 上传视频

本文详细介绍如何在Vue项目中整合富文本编辑器,实现图片和视频的上传及展示功能,包括使用vue-quill-editor、quill-image-extend-module等插件,并通过axios进行前后端交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目需要,看了很多博客,都不太合适,于是东拼西凑的做了这个功能

使用插件:
vue-quill-editor
quill-image-extend-module
BootstrapVue
axios
请自行 install 和 import
先看看效果吧
效果
下面就是代码:

<template>
  <!-- bidirectional data binding(双向数据绑定) -->
  <div class="testFweb_box">
    <div class="testFweb">
      <quill-editor v-model="content"
        value="editorVal"
        ref="myQuillEditor"
        :options="editorOption">
      </quill-editor>
    </div>
    <!-- 视频上传 -->
    <div class="floatBox" v-show='upvideoShow'>
      <div class="floatsmBox">
        <b-form-file accept="video/*" v-model="videofile" ref="videofilereset" placeholder="选择视频文件"></b-form-file>
        <span style="margin-top: 10px;" class="btn btn-outline-success" @click='upVideo'>确认</span>
        <span style="margin-top: 10px;" class="btn btn-outline-success" @click='cancelupVideo'>取消</span>
      </div>
    </div>
    <!-- 图片上传 -->
    <div class="floatBox" v-show='upimgShow'>
      <div class="floatsmBox">
        <b-form-file accept="image/*" v-model="imgfile" ref="imgfilereset" placeholder="选择图片文件"></b-form-file>
        <span style="margin-top: 10px;" class="btn btn-outline-success" @click='upImg'>确认</span>
        <span style="margin-top: 10px;" class="btn btn-outline-success" @click='cancelupImg'>取消</span>
      </div>
    </div>
    <div style="display: none;" id="upvideoshow" @click='upvideoShow=true'></div>
    <div style="display: none;" id="upimgshow" @click='upimgShow=true'></div>
    <div v-if='showFloat' class='floatBox ub ub_ac ub_pc'>
      <b-progress class='ub_f1 proessBox' :value="jindu" :max="100" show-progress animated></b-progress>
    </div>
  </div>
</template>
<style>
  .proessBox{
    max-width: 400px;
  }
  .testFweb{
    width: 800px;
    margin: 50px auto;
  }
  .testFweb_box .custom-file-label::after{
    content: "选择视频文件";
    display: none;
  }
  .floatsmBox{
    padding: 20px;
    background-color: #fff;
    margin-top: 5%;
  }
  .floatBox{
    position: fixed;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0,0.2);
    width: 100%;
    height: 100%;
    padding: 0 10%;
    z-index: 10;
  }
</style>
<script>
  import {quillEditor, Quill} from 'vue-quill-editor'
  import {container} from 'quill-image-extend-module'  
  export default {
    components: {quillEditor,},
    data () {
      return {
        showFloat:false,//控制上传进度展示浮层
        jindu:0,//上传进度
        upvideoShow:false,//控制上传视频展示
        upimgShow:false,//控制上传图片展示
        videofile:'',
        imgfile:'',
        content: '',//编辑器内容
        editorVal:'',
        editorOption: {
          modules: {
            toolbar: {  // 如果不上传图片到服务器,此处不必配置
              container: [
                  [{'size': ['small', false, 'large', 'huge']}],
                  [{'align': []}],
                  ['link', 'image', 'video']
              ],  // container为工具栏,可自行配置
              handlers: {
                'image': function () {  // 劫持原来的图片点击按钮事件
                  document.querySelector('#upimgshow').click()
                },
                'video':function(val){
                  document.querySelector('#upvideoshow').click()
                }
              }
            }
          },
          theme: 'snow',
          placeholder: '填写内容',
        }  // 必须初始化为对象 init  to Object
      }
    },
    methods:{
      cancelupImg(){//取消上传图片 关闭浮层并清除文件
        this.$refs.imgfilereset.reset();
        this.upimgShow = false 
      },
      cancelupVideo(){//取消上传视频 关闭浮层并清除文件
        this.$refs.videofilereset.reset();
        this.upvideoShow = false
      },
      upImg(){//上传图片
        var that = this
        if(!that.$isDefine(that.imgfile)){
          that.$alert('请选择图片')
        }
        that.jindu = 0
        that.showFloat = true
        //随机9位数名称(由于此项目文件是上传到阿里云的oss上面的,所以同一天的同名文件会覆盖,按需添加)
        var a = that.imgfile.name
        var eame = a.split('.')
        var rnd="";
        for(var i=0;i<9;i++){rnd+=Math.floor(Math.random()*10);}
        let param = new FormData(); //创建form对象
        param.append('img',that.imgfile,rnd+'.'+eame[eame.length-1]);//视频
        let config = {
          onUploadProgress: progressEvent => {
            var complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
            // console.log('进度值',complete)
            that.jindu = complete
          },
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        that.axios.post('url',param,config)//url为上传地址
        .then(response=>{
          that.$refs.imgfilereset.reset();//清除文件
          if (response.data.error == '0') {
            // 获取光标所在位置
            let quill = that.$refs.myQuillEditor.quill
            let length = quill.getSelection().index;
            // 插入图片  response.data.url为服务器返回的图片地址
            quill.insertEmbed(length, 'image', response.data.url)
            // 调整光标到最后
            quill.setSelection(length + 1)
            that.showFloat = false
            that.upimgShow = false
          } else {
            that.showFloat = false
            that.upimgShow = false
            this.$alert('插入失败,请重试')
          }
        }).
        catch(function(error){
          that.$alert('插入失败,请重试')
          that.showFloat = false
          that.upimgShow = false
        })  
      },
      upVideo(){//上传视频
        var that = this
        if(!that.$isDefine(that.videofile)){
          that.$alert('请选择视频')
        }
        that.jindu = 0
        that.showFloat = true
        //随机9位数名称(由于此项目的视频是上传到阿里云的oss上面的,所以同一天的同名文件会覆盖)
        var a = that.videofile.name
        var eame = a.split('.')
        var rnd="";
        for(var i=0;i<9;i++){rnd+=Math.floor(Math.random()*10);}
        let param = new FormData(); //创建form对象
        param.append('video',that.videofile,rnd+'.'+eame[eame.length-1]);//视频
        let config = {
          onUploadProgress: progressEvent => {
            var complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
            // console.log('进度值',complete)
            that.jindu = complete
          },
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        that.axios.post('url',param,config)//url为上传地址
        .then(response=>{
          that.$refs.videofilereset.reset();//清除文件
          if (response.data.error == '0') {
            // 获取光标所在位置
            let quill = that.$refs.myQuillEditor.quill
            let length = quill.getSelection().index;
            // 插入视频  response.data.url为服务器返回的图片地址
            quill.insertEmbed(length, 'video', response.data.url)
            // 调整光标到最后
            quill.setSelection(length + 1)
            that.showFloat = false
            that.upvideoShow = false
          } else {
            that.showFloat = false
            that.upvideoShow = false
            this.$alert('插入失败,请重试')
          }
        }).
        catch(function(error){
          that.$alert('插入失败,请重试')
          that.showFloat = false
          that.upvideoShow = false
        })  
      }
    },
  }
</script>

注意

$alert();$isDefine()是我自己封装的方法,前者为弹出框,后者为判断字段是否为空、null、undefined等,自行封装

后台返回

成功返回
成功返回
错误返回
error不为0即可

### 回答1: vue-quill-editor可以通过插件实现上传视频的功能。具体步骤如下: 1. 安装插件:可以使用vue-quill-editor-video-uploader插件,通过npm安装即可。 2. 引入插件:在main.js中引入插件并注册。 3. 配置插件:在vue-quill-editor的配置项中添加videoUploader配置项,指定上传视频的接口地址、上传成功后的回调函数等。 4. 在quill-editor组件中添加video模块:在quill-editor组件的modules属性中添加video模块,使其支持插入视频。 5. 在quill-editor组件中添加上传视频按钮:在quill-editor组件中添加一个上传视频的按钮,点击后触发上传视频的操作。 以上就是使用vue-quill-editor上传视频的基本步骤,具体实现可以参考插件的文档和示例代码。 ### 回答2: vue-quill-editor是一款基于Vue.js的富文本编辑器插件,提供了丰富的文本编辑功能,例如添加图片、文字格式化等。在有些场景下,我们可能需要在文本中插入视频。本文将介绍使用vue-quill-editor上传视频的方法。 1. 安装需要的依赖 首先,我们需要安装一些开发依赖,可以使用npm或者yarn安装。命令如下: ``` npm install --save quill-image-resize-module ``` ``` npm install --save vue-quill-editor ``` 2. 引入依赖 在Vue组件中引入依赖,代码如下: ``` import Vue from 'vue' import VueQuillEditor from 'vue-quill-editor' import { quillEditor } from 'vue-quill-editor' import Quill from 'quill' import ImageResize from 'quill-image-resize-module' Vue.use(VueQuillEditor, {}) Quill.register('modules/imageResize', ImageResize) export default { components: { quillEditor } } ``` 这里我们引入了vue-quill-editorquill-editor等插件,以及quill-image-resize-module来支持视频大小调整。 3. 添加视频上传功能 接下来,我们要添加上传视频功能。我们可以使用Fetch API来上传视频。我们可以添加一个addVideo方法处理上传事件,代码如下: ``` <template> <quill-editor ... :modules="modules" ... ></quill-editor> </template> <script> export default { data () { return { modules: { toolbar: [ ... { name: 'video', icon: 'fa fa-file-video-o', handler: this.addVideo } ] ... } } }, methods: { addVideo () { const input = document.createElement('input') input.setAttribute('type', 'file') input.setAttribute('accept', 'video/mp4,video/3gpp,video/x-msvideo') input.onchange = () => { const file = input.files[0] const formData = new FormData() formData.append('file', file) const xhr = new XMLHttpRequest() xhr.open('POST', '/api/upload', true) xhr.onload = () => { if (xhr.status === 200) { const res = JSON.parse(xhr.responseText) const url = res.data.url const range = this.quill.getSelection() this.quill.insertEmbed(range.index, 'video', url) } } xhr.send(formData) } input.click() } } } </script> ``` 在这段代码中,我们首先定义了一个input元素来选择并上传视频上传完成后,我们根据响应中的url插入视频,以及定义了Toolbar中的video图标来触发上传事件。 需要注意的是,需要指定上传视频的格式类型,这里我们指定为mp4和3gp格式。 4. 完整代码 完整的Vue组件代码如下: ``` <template> <quill-editor v-model="content" :options="editorOption" :modules="modules" ></quill-editor> </template> <script> import Vue from 'vue' import _ from 'lodash' import Quill from 'quill' import { quillEditor } from 'vue-quill-editor' import ImageResize from 'quill-image-resize-module' Vue.use(Quill, { modules: { ImageResize } }) export default { components: { quillEditor }, props: { value: String, height: { default: '400px', type: String } }, data () { return { content: '', editorOption: { placeholder: '', readOnly: false, modules: { toolbar: [ [{ header: [1, 2, false] }], ['bold', 'italic', 'underline'], [{ color: [] }, { background: [] }], [{ font: [] }], [{ align: [] }], ['link'], ['image'], ['video'], ['clean'] ] }, theme: 'snow' }, modules: { imageResize: { displaySize: true }, toolbar: [ [{ header: [1, 2, false] }], ['bold', 'italic', 'underline'], [{ color: [] }, { background: [] }], [{ font: [] }], [{ align: [] }], [{ list: 'ordered' }, { list: 'bullet' }], [{ indent: '-1' }, { indent: '+1' }], ['link', 'image', 'video'], ['clean'] ] } } }, mounted () { if (!_.isEmpty(this.value)) { this.content = this.value } }, watch: { value (val) { if (!_.isEmpty(val)) { this.content = val } }, content (val) { this.$emit('input', val) } }, methods: { addVideo () { const input = document.createElement('input') input.setAttribute('type', 'file') input.setAttribute('accept', 'video/mp4,video/3gpp,video/x-msvideo') input.onchange = () => { const file = input.files[0] const formData = new FormData() formData.append('file', file) const xhr = new XMLHttpRequest() xhr.open('POST', '/api/upload', true) xhr.onload = () => { if (xhr.status === 200) { const res = JSON.parse(xhr.responseText) const url = res.data.url const range = this.quill.getSelection() this.quill.insertEmbed(range.index, 'video', url) } } xhr.send(formData) } input.click() } } } </script> ``` 5. 注意事项 需要注意的是,这段代码中的视频上传接口是一个示例,我们需要根据自己的实际情况来替换上传接口,同时修改响应中的url取值方式来确保能够插入视频。此外,我们需要根据自己的需求来修改Toolbar中的按钮配置。 ### 回答3: 在Vue-quill-editor中,上传视频可以使用自定义模块中的方法来实现。以下是实现的几个步骤: 1. 安装依赖:需要安装quillquill-upload-video插件,可以通过使用npm或yarn安装。命令如下: npm install quill quill-upload-video 2. 引入依赖:在需要使用富文本编辑器的组件中引入quillquill-upload-video插件,代码如下: import VueQuillEditor from 'vue-quill-editor' import 'quill/dist/quill.core.css' import 'quill/dist/quill.snow.css' import 'quill/dist/quill.bubble.css' import QuillVideo from 'quill-upload-video' import 'quill-upload-video/dist/quill.uploadVideo.css' Vue.use(VueQuillEditor) Quill.register('modules/uploadVideo', QuillVideo) 3. 配置Vue-quill-editor:在使用Vue-quill-editor的模板中,需要配置以下属性: <vue-quill-editor :options='{ modules: { uploadVideo: { server: '/api/uploadVideo', fieldName: 'file', types: ['video/mp4'] } } }' ... /> 其中,options属性中的modules对象中配置了uploadVideo模块。其中的server属性是上传视频的后台API地址;fieldName属性是上传视频的后台API中接收文件流的字段名;types属性是用于校验上传视频文件类型的数组。 4. 上传视频:在编辑器中插入视频时,需要使用uploadVideo模块提供的insertVideo方法。代码如下: this.$refs.editor.quill.getModule('uploadVideo').insertVideo(url, name) 其中,url是分配的视频资源地址,name是视频名称。这两个参数可以通过后台API返回。 以上就是Vue-quill-editor上传视频的基本实现流程。需要注意的是,上传视频时应该考虑视频大小、文件类型和服务器端等因素。在实现时,可以结合业务需求进行相关的处理。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值