wangEditor上传本地视频/本地图片至阿里云oss并回显

1.上传本地图片至oss并且回显至富文本

先创建oss.js上传/图片/视频接口

import request from '@/utils/re.js'   //封装的请求

import axios from 'axios'

export function policy1() {

  return request({

    url:'url',//上传接口

    method:'get',

  })

}

export function getUUID () {

return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {

  return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)

})

}

export function ossUpload (file,editor) {

  var that = this;

  return new Promise((resolve, reject) => {

      policy1().then((response) => {

      const formData = new FormData()

      formData.append('OSSAccessKeyId', response.data.accessKeyId)

      formData.append('policy', response.data.policy)

      formData.append('signature', response.data.signature)

      formData.append('key', response.data.dir +getUUID() +'_'+ file.name)

      formData.append('callback', response.data.callback)

      formData.append('file', file)

      formData.append('host',response.data.host)

      axios.post(response.data.host, formData).then((res) => {

        const { status } = res

        if (status === 200) {

          console.log('200',res)

            editor.cmd.do('insertHTML', `<img src=${res.data.data.filename} alt="">`)

          return res.data

        } else {

        }

      }).catch(err => {

        console.log(1111,err)

      })

    }).catch(err => {})

  })

}

创建wangEditor.vue组件

<template lang="html">

  <div class="editor">

    <div ref="toolbar" class="toolbar">

    </div>

    <div ref="editor" class="text">

    </div>

  </div>

</template>

<script>

  import E from 'wangeditor'

  import { ossUpload } from '@/api/oss'

  export default {

    name: 'editor',

    data() {

      return {

        // uploadPath,

        editor: null,

        info_: null,

          menus: [

          'head', // 标题

          'bold', // 粗体

          'fontSize', // 字号

          'fontName', // 字体

          'italic', // 斜体

          'underline', // 下划线

          'strikeThrough', // 删除线

          'foreColor', // 文字颜色

          'backColor', // 背景颜色

          'link', // 插入链接

          'list', // 列表

          'justify', // 对齐方式

          'quote', // 引用

          'emoticon', // 表情

          'image', // 插入图片

          'table', // 表格

          'video', // 插入视频

          'code', // 插入代码

          'undo', // 撤销

          'redo', // 重复

          'fullscreen' // 全屏

                ]

      }

    },

    model: {

      prop: 'value',

      event: 'change'

    },

    props: {

      value: {

        type: String,

        default: ''

      },

      isClear: {

        type: Boolean,

        default: false

      }

    },

    watch: {

      isClear(val) {

        // 触发清除文本域内容

        if (val) {

          this.editor.txt.clear()

          this.info_ = null

        }

      },

      value: function(value) {

        if (value !== this.editor.txt.html()) {

          this.editor.txt.html(this.value)

        }

      }

      //value为编辑框输入的内容,这里我监听了一下值,当父组件调用得时候,如果给value赋值了,子组件将会显示父组件赋给的值

    },

    mounted() {

      this.seteditor()

      this.editor.txt.html(this.value)

    },

    methods: {

      seteditor() {

        this.editor = new E(this.$refs.toolbar, this.$refs.editor);

        this.editor.customConfig = this.editor.customConfig ? this.editor.customConfig : this.editor.config;

        this.editor.customConfig.customUploadImg = async (files, insert) => {

                  const res = await ossUpload(files[0],this.editor)

                }

        this.editor.customConfig.menus = this.menus;

      //连接

      this.editor.customConfig.linkCheck = function (text, link) {

          console.log("插入的文字",text) // 插入的文字

          console.log("插入的链接",link) // 插入的链接

          return true // 返回 true 表示校验成功

      },

        this.editor.customConfig.onchange = (html) => {

          this.info_ = html // 绑定当前逐渐地值

          this.$emit('change', this.info_) // 将内容同步到父组件中

        }

        // 创建富文本编辑器

        this.editor.create()

      }

    }

  }

</script>

<style lang="css">

  .editor {

    width: 100%;

    margin: 0 auto;

    position: relative;

    z-index: 0;

  }

  .toolbar {

    border: 1px solid #ccc;

  }

  .text {

    border: 1px solid #ccc;

    min-height: 500px;

  }

</style>

效果:

2.上传本地视频至oss

因为wangEditor本身只能通过链接插入视频,不能实现上传本地视频,所以我总结多方网络经验,自己手扣了一个(就是通过ElementUI上传组件实现,拿到最终图片路径后再放进富文本,思路大概就是这样。但是插入的视频不能改变大小,如果有实现的小伙伴,就麻烦给我指点一下哈哈哈)

新建组件wangEndtorArticle.vue:(该组件功能比较完整,包括上面的上传图片)

<template>

  <div style="display: inline-flex;">

    <div class="img-list-item common mb_10" v-for="(item,index) in dialogImageUrl">

      <video width="150px" height="150px" style="padding: 0 5px;" controls="controls" :src="item"> 您的浏览器不支持视频播放</video>

      <i class="del-img" @click="forkImage(index)"></i>

    </div>

    <el-upload action="https://wtwf-product.oss-cn-chengdu.aliyuncs.com"

              :data="dataObj" :show-file-list="false"

              :auto-upload="true"

              :on-remove="handleRemove"

              :on-success="handleUploadSuccess"

              :before-upload="beforeUpload"

              :limit="maxCount"

              accept=".mp4"

              :on-exceed="handleExceed"

              :on-progress="uploadVideoProcess">

      <span class="warp">

        <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;position: relative;top: -15px;">

        </el-progress>

        <i v-else class="el-icon-plus" :style="{fontSize: '18px',fontWeight:'bold',padding:paddings,position:'relative',top:'60px'}"></i>

      </span>

    </el-upload>

  </div>

</template>

<script>

  import {

    policy1

  } from '@/api/oss'

  export default {

    props: {

      value: Array,

      //最大上传图片数量

      maxCount: {

        type: Number,

        default: 5

      },

      w: {

        type: String,

        // default:'100px'

      },

      h: {

        type: String,

        // default:'100px'

      },

      paddings: {

        type: String,

      }

    },

    data: function() {

      return {

        videoFlag: false,

        videoUploadPercent: 0,

        videis: false,

        dataObj: {

          policy: '',

          signature: '',

          key: '',

          ossaccessKeyId: '',

          dir: '',

          host: ''

        },

        dialogVisible: false,

        dialogImageUrl: []

      }

    },

    computed: {

      fileList() {

        let fileList = [];

        for (let i = 0; i < this.value.length; i++) {

          fileList.push({

            url: this.value[i]

          });

        }

        console.log('视频---->', fileList);

        console.log('视频22222222222222---->', this.dialogImageUrl);

        return fileList;

      }

    },

    methods: {

      //删除视频

      forkImage(index) {

        // console.log('当前索引', index);

        this.dialogImageUrl.splice(index, 1);

        // console.log('删除后的数组数组', this.dialogImageUrl);

      },

      getUUID() {

        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {

          return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)

        })

      },

      emitInput(fileList) {

        let value = [];

        for (let i = 0; i < fileList.length; i++) {

          value.push(fileList[i].url);

        }

        this.$emit('input', value)

      },

      handleRemove(file, fileList) {

        this.emitInput(fileList)

      },

      handleUploadSuccess(res, file) {

        // console.log("成功后", file)

        // console.log('获取图片', res.data);

        let url = this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name);

        // console.log('路径', url);

        this.fileList.push({

          name: file.name,

          url: url

        });

        this.dialogVisible = true;

        this.dialogImageUrl.push(url);

        // console.log("视频地址", this.);

        this.emitInput(this.fileList);

        this.videoFlag = false;

        this.videoUploadPercent = 0;

      },

      uploadVideoProcess(event, file, fileList) {

        this.videoFlag = true;

        this.videoUploadPercent = Math.floor(event.percent);

      },

      beforeUpload(file) {

        var fileSize = file.size / 1024 / 1024 < 100;

        console.log('视频大小', fileSize);

        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) ==

          -1) {

          this.$message({

            type: 'warning',

            message: '请上传正确的视频格式'

          });

          return false;

        }

        if (!fileSize) {

          this.$message({

            type: 'warning',

            message: '视频大小不能超过100MB'

          });

          return false;

        }

        this.videoFlag = true;

        console.log("上传视频值", file);

        const _self = this

        return new Promise((resolve, reject) => {

          policy1().then(response => {

            console.log("视频---->获取数据", response.data);

            _self.dataObj.policy = response.data.policy;

            // console.log('policy值',response.data.policy);

            _self.dataObj.signature = response.data.signature;

            // console.log('signature值',response.data.signature);

            _self.dataObj.ossaccessKeyId = response.data.accessKeyId;

            // console.log('ossaccessKeyId值',response.data.accessKeyId);

            _self.dataObj.key = response.data.dir + this.getUUID() + '_${filename}';

            console.log('视频---->key值', response.data.dir + this.getUUID() + '_${filename}');

            _self.dataObj.dir = response.data.dir;

            console.log('视频---->dir值', response.data.dir);

            _self.dataObj.host = response.data.host;

            _self.dataObj.callback = response.data.callback;

            resolve(true)

          }).catch(err => {

            console.log(err)

            reject(false)

          })

        })

      },

      handlePreview(file) {

        // console.log('获取视频', file.url);

        this.dialogVisible = true;

        this.dialogImageUrl = file.url;

      },

      handleExceed(files, fileList) {

        // console.log("获取上传视频", files, fileList);

        this.$message({

          message: '最多只能上传' + this.maxCount + '个视频',

          type: 'warning',

          duration: 1000

        });

      },

    }

  }

</script>

<style lang="scss" scoped>

  .warp {

    display: inline-block;

    // padding: 54px 64px;

    width: 150px;

    height: 151px;

    border: 1px dashed #DEE5ED;

  }

  /deep/.el-upload-list {

    display: none;

  }

  .el-upload-video {

    width: 149px;

    height: 149px;

    border: 1px dashed #d9d9d9;

    border-radius: 6px;

    cursor: pointer;

    position: relative;

    overflow: hidden;

  }

  .el-upload-video-i {

    font-size: 20px;

    font-weight: bold;

    padding-top: 43px;

    color: #8c939d;

    width: 50px;

    height: 50px;

    line-height: 50px;

    text-align: center;

  }

  //视频

  .img-list-item {

    position: relative;

    margin: auto;

  }

  // .img-list-item img {

  //  box-sizing: border-box;

  //  vertical-align: middle;

  //  border: 0;

  // }

  .img-list-item i.del-img {

    width: 20px;

    height: 20px;

    display: inline-block;

    background: rgba(0, 0, 0, .6);

    background-image: url(../assets/images/close.png);

    background-size: 18px;

    background-repeat: no-repeat;

    background-position: 50%;

    position: absolute;

    top: 0;

    right: -1px;

  }

</style>

3.页面调用

<editor-bar v-model="detail" :isClear="isClear" ></editor-bar>

import EditorBar from '../../../components/wangEndtorArticle.vue'   //引入组件

export default {

    components: {

      EditorBar   //注册组件

    },

    data() {

      return {

               detail:"   "  //存放富文本内容

               }

}

}

效果:

查看了很多资料,有些忘记保存                      请看过的小伙伴们留个赞哟(前端小白请各位大佬多多指教)!!!!

https://blog.csdn.net/weixin_45455422/article/details/106380143?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-9.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-9.control

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容