vue 视频上传组件

在这里插入图片描述

组件:

<template>
  <div class="upload-box">
    <div class="avatar-uploader-box">
      <!-- 图片预览 -->
      <div :key="index" class="video-preview" v-for="(item, index) in videoList">
        <video v-if="item.videoLink" :src="`${videoBaseUrl}${item.videoLink}`" @mouseover.stop="item.isShowPopup = true" class="avatar">
          您的浏览器不支持视频播放
        </video>
        <video v-else :src="item.url" @mouseover.stop="item.isShowPopup = true" class="avatar">
          您的浏览器不支持视频播放
        </video>
        <!-- 显示查看和删除的按钮弹窗 -->
        <div
          @mouseleave="item.isShowPopup = false"
          class="avatar-uploader-popup"
          v-show="(item.videoLink || item.url) && item.isShowPopup"
        >
          <i @click="previewVideo(item)" class="el-icon-zoom-in"></i>
          <i @click="deleteVideo(index)" class="el-icon-delete"></i>
        </div>
      </div>

      <!-- 方框样式 -->
      <el-upload
        :action="actionUrl"
        :auto-upload="false"
        :on-change="handleAvatarChange"
        :show-file-list="false"
        class="avatar-uploader"
        ref="avatarUploader"
        v-show="uploadShow"
      >
        <span
          element-loading-background="rgba(0, 0, 0, 0.8)"
          element-loading-spinner="el-icon-loading"
          element-loading-text="上传中"
          style="display:block;"
          v-loading="loading"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </span>
      </el-upload>

      <!-- 上传提示文字样式 -->
      <div class="upload-tip">
        <slot></slot>
      </div>
    </div>

    <!-- 查看大图 -->
    <el-dialog :visible.sync="dialogVisible" append-to-body center title="视频查看" :before-close="handleClose">
      <video :src="videoSrc" ref="video" controls alt width="100%">您的浏览器不支持视频播放</video>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UploadVideo',
  components: {},
  props: {
    videos: {
      type: Array,
      default: function() {
        return []
      }
    },
    numLimit: {
      // 最大允许上传个数
      type: Number,
      default: 1
    },
    sizeLimit: {
      // 最大单文件大小
      type: Number,
      default: 50
    },
    videoBaseUrl: {
      // 已上传图片服务器路径
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      videoList: [],
      videoSrc: '',
      actionUrl: ''
    }
  },
  computed: {
    uploadShow() {
      return this.videos.length < this.numLimit
    }
  },
  watch: {
    videos: {
      handler() {
        const isArray = Array.isArray(this.videos)
        if (isArray && this.videos.length > 0) {
          this.videos.map(item => {
            item.isShowPopup = false
          })
          this.videoList = JSON.parse(JSON.stringify(this.videos))
        } else {
          this.videoList = []
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {},
  methods: {
    // 上传之前
    beforeAvatarUpload(file) {
      return new Promise((resolve, reject) => {
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.raw.type) == -1) {
          // eslint-disable-next-line prefer-promise-reject-errors
          return reject('请上传正确的视频格式!')
        }

        if (file.size / 1024 / 1024 > this.sizeLimit) {
          // eslint-disable-next-line prefer-promise-reject-errors
          return reject(`视频大小不能超过${this.sizeLimit}M!`)
        }

        if (this.videoList.length === this.numLimit) {
          // eslint-disable-next-line prefer-promise-reject-errors
          return reject(`最多上传${this.numLimit}个视频`)
        }

        resolve('符合表單規則')
      })
    },
    // 上传改变
    async handleAvatarChange(file, fileList) {
      try {
        await this.beforeAvatarUpload(file)
        this.uploadImgApi(file)
      } catch (e) {
        this.$message.warning(JSON.stringify(e))
      }
    },
    // 上传视频准备
    uploadImgApi(data) {
      console.log(data, 'upload**')
      const videoSrc = URL.createObjectURL(data.raw)
      this.videoList.push({
        videoFile: data,
        url: videoSrc,
        isShowPopup: false
      })
      this.$emit('change', this.videoList)
    },
    // 预览视频
    previewVideo(data) {
      if (data.videoLink) {
        this.videoSrc = `${this.videoBaseUrl}${data.videoLink}`
      } else {
        this.videoSrc = data.url
      }
      this.dialogVisible = true
    },
    // 删除视频
    deleteVideo(index) {
      this.$emit('delete', index)
    },
    handleClose() {
      const video = document.getElementsByTagName('video')[1]
      if (!video.paused) {
        video.currentTime = 0
        video.pause()
      }
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss">
$width: 90px;
$height: 90px;

.upload-box {
  .avatar-uploader-box {
    position: relative;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    padding-bottom: 20px;
    min-width: 350px;
    .avatar-uploader {
      .el-upload {
        width: $width;
        height: $height;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
          border-color: #409eff;
        }
        .el-loading-spinner {
          width: $width;
          height: $height;
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-top: 0;
          top: 0;
          .el-loading-text {
            margin: 0;
          }
        }
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: $width;
        height: $height;
        line-height: $height;
        text-align: center;
      }
    }
    .video-preview {
      position: relative;
      padding-right: 20px;
      .avatar {
        width: $width;
        height: $height;
        display: block;
        border-radius: 6px;
      }
      .avatar-uploader-popup {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: $width;
        height: $height;
        background: rgba($color: #000000, $alpha: 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        font-size: 20px;
        border-radius: 6px;
        i {
          width: 30%;
          text-align: center;
          padding: 0 5%;
          font-size: 24px;
        }
      }
    }
    .upload-tip {
      position: absolute;
      bottom: 0;
      left: 0;
      font-size: 12px;
      color: #606266;
      max-width: 350px;
      line-height: 20px;
    }
  }
}
</style>

页面引入:

import UploadVideo from '@c/UploadVideo'
components: { UploadVideo }
<upload-video
  :videos="videoInfo.allVideo"
  :videoBaseUrl="IMAGEURL"
  @delete="deleteVideo"
  @change="getVideo" >
</upload-video>

data数据:

videoInfo: {
   allVideo: [],
   deleteVideo: []
}

视频上传:(此处只是上传到暂存区,真正上传是在提交表单时)

getVideo(event) {
  this.videoInfo.allVideo = event
}

视频删除:

deleteVideo(index) {
  const video = this.videoInfo.allVideo[index]
  if (video.videoLink) {
  this.videoInfo.deleteVideo.push(video)
  }
  this.videoInfo.allVideo.splice(index, 1)
}

在提交表单时上传:

uploadFiles() {
  const uploadList = []
  this.videoInfo.allVideo.map(item => {
        console.log(item, 'video')
        const videoFile = new FormData()
        if (!item.videoLink) {
          videoFile.append('file', item.videoFile.raw)
          videoFile.append('fileTag', 'video')
          uploadList.push(
            new Promise((resolve, reject) => {
              return ImgServe.uploadSingleFile(videoFile).then(res => {
                if (res.data.code === 200) {
                  resolve(res.data.data)
                } else {
                  this.$message('上传视频失败!')
                }
              })
            })
          )
        }
      })
      return Promise.all(uploadList)
}

*:分开上传是为了杜绝服务器脏数据
ImgServe.uploadSingleFile(videoFile)这儿是上传到服务器的接口,替换为自己的写法即可

Vue前端上传组件可以使用第三方库如`element-ui`的`el-upload`组件来实现上传图片和视频的功能。 首先,需要在Vue项目中引入`element-ui`库: ```javascript import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) ``` 然后,在需要使用上传组件的页面中,可以使用`el-upload`组件来实现上传图片和视频的功能。以下是一个示例: ```html <template> <div> <el-upload class="upload-demo" action="/upload" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :file-list="fileList" :accept="'image/*,video/*'" > <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传图片或视频</div> </el-upload> </div> </template> <script> export default { data() { return { fileList: [] } }, methods: { beforeUpload(file) { const isImage = file.type.indexOf('image') !== -1 const isVideo = file.type.indexOf('video') !== -1 const isLt2M = file.size / 1024 / 1024 < 2 if (!isImage && !isVideo) { this.$message.error('请选择图片或视频文件') return false } if (!isLt2M) { this.$message.error('上传文件大小不能超过 2MB') return false } }, handleSuccess(response, file, fileList) { console.log(response, file, fileList) this.fileList = fileList.slice(-1) }, handleError(error, file, fileList) { console.log(error, file, fileList) this.$message.error('上传失败') } } } </script> ``` 其中,`el-upload`组件的`accept`属性可以用来限制上传文件的类型,本示例中使用`image/*,video/*`表示只允许上传图片或视频文件;`beforeUpload`方法用来在上传前进行文件类型和大小的校验;`handleSuccess`和`handleError`方法分别用来处理上传成功和失败的情况。 需要注意的是,上传文件的具体实现需要在后端服务器中完成。在本示例中,`action`属性指定了上传文件的后端接口地址为`/upload`,具体实现需要后端开发人员完成。
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱喝冰可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值