欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-22 14:00:42
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 ge...

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>

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

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=""
              :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: Arry,
      //最大上传图片数量
      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:"   "  //存放富文本内容

               }

}

}


效果
wangEditor上传本地视频/本地图片至阿里云oss并回显
wangEditor上传本地视频/本地图片至阿里云oss并回显
查看了很多资料和其它博主写的,有些忘记保存 请看过的小伙伴们留个赞哟(前端小白请各位大佬多多指教)!!!!

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(研究了很多天,只记得这一个网址了,有原创若看到,可以私聊我哟,转发请注明原创)

本文地址:https://blog.csdn.net/oneya1/article/details/112586077