tinyMCE本地视频上传

摘要

期望:在tinyMCE富文本编辑器中将本地图片上传至服务器

背景:vue tinyMCE^4.7.4

步骤:1.在工具栏toolbar中显示视频图标

           2.在弹出的媒体窗口中添加本地上传图标

           3.视频上传服务器并将视频添加入编辑内容中

           4.优化:a.显示上传状态 

文章示例代码地址:https://codepen.io/hanxyan/pen/LMeLZj

正文

1.在工具栏toolbar中显示视频图标

代码:

import tinymce from 'tinymce';
import 'tinymce/plugins/media'//本地npm安装后,提示找不到media插件,加入这个引用。

const setting ={
  selector: '#editor',
  plugins: "media",//插件
  menubar: "insert",
  toolbar: "media"//在工具栏显示media图标
};

添加后的效果:

2.在弹出的媒体窗口中添加本地上传图标

在设置file_picker_types为 'media'。

代码:

const setting={
                selector: `#${self.id}`,
                plugins: 'media',
                toolbar: 'undo redo | link media',
                //想要哪一个图标提供本地文件选择功能,参数可为media(媒体)、image(图片)、file(文件)
                file_picker_types: 'media', 
                //be used to add custom file picker to those dialogs that have it.
                file_picker_callback: function(cb, value, meta) {
                  
                }
            }

效果:

3.视频上传服务器并将视频添加入编辑内容中

通过配置file_picker_callback实现上传

代码:

new Vue({
  el: '#app',
  data() {
    return {
        id:'editor',
        apiUrl:'upload/server/api',//视频文件上传接口
        credentials:true
      }
  },
  methods:{
        editorInit(){
            let self=this;
            const setting={
                selector: `#${self.id}`,
                plugins: 'media',
                toolbar: 'undo redo | link media',
                //想要哪一个图标提供本地文件选择功能,参数可为media(媒体)、image(图片)、file(文件),多个参数用空格分隔
                file_picker_types: 'media', 
                //be used to add custom file picker to those dialogs that have it.
                file_picker_callback: function(cb, value, meta) {
                  //当点击meidia图标上传时,判断meta.filetype == 'media'有必要,因为file_picker_callback是media(媒体)、image(图片)、file(文件)的共同入口
                  if (meta.filetype == 'media'){
                    //创建一个隐藏的type=file的文件选择input
                    let input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    input.onchange = function(){
                      let file = this.files[0];
                      var xhr, formData;
                      xhr = new XMLHttpRequest();
                      xhr.open('POST', self.apiUrl);
                      xhr.withCredentials = self.credentials;
                      xhr.upload.onprogress = function (e) {
                        // 进度(e.loaded / e.total * 100)
                      };
                      xhr.onerror = function () {
                        //根据自己的需要添加代码
                        console.log(xhr.status);
                        return;
                      };
                      xhr.onload = function () {
                        let json;
                        if (xhr.status < 200 || xhr.status >= 300) {
                          console.log('HTTP 错误: ' + xhr.status);
                          return;
                        }
                        json = JSON.parse(xhr.responseText);
                        //假设接口返回JSON数据为{status: 0, msg: "上传成功", data: {location: "/localImgs/1546434503854.mp4"}}
                        if(json.status==0){
                          //接口返回的文件保存地址
                          let mediaLocation=json.data.location;
                          //cb()回调函数,将mediaLocation显示在弹框输入框中
                          cb(mediaLocation, { title: file.name });
                        }else{
                          console.log(json.msg);
                          return;
                        }
                        
                      };
                      formData = new FormData();
                      //假设接口接收参数为file,值为选中的文件
                      formData.append('file', file);
                      //正式使用将下面被注释的内容恢复
                      xhr.send(formData);
                    }
                    //触发点击
                    input.click();
                  }
                }
            }
            tinymce.init(setting);
         }
        },
  mounted(){
    this.editorInit();
  },
  beforeDestroy:function(){
    tinymce.get(`#${this.id}`).destroy();
  }
})

备注:如果在项目中会频繁地使用到xhr,那么最好把xhr封装,然后放在一个单独的文件中。这样可以减少重复操作,简化代码。

效果:

4.优化

a.显示上传状态 

上传视频的时候,如果视频文件比较大,花费的时间比较长。

但是在上传过程中(接口处于pending状态时),页面竟然没有显示上传中的状态,无法辨别是文件没选中还是没上传成功。

在xhr的progress事件中使用tinyMCE的setProgressState()方法显示加载状态。

xhr.upload.onprogress = function (e) {
   // 进度(e.loaded / e.total * 100)
   let percent=e.loaded / e.total * 100;
   if(percent<100){
         tinymce.activeEditor.setProgressState(true);//是否显示loading状态:1(显示)0(隐藏)
   }else{
         tinymce.activeEditor.setProgressState(false);
   }
};
xhr.onerror = function () {
   console.log(xhr.status);
   tinymce.activeEditor.setProgressState(false);
   return;
};

猜你喜欢

转载自blog.csdn.net/Sarahhoney12_/article/details/85629014