vue通过七牛云上传视频并获取封面

vue通过七牛云上传视频并获取封面

1.引入七牛云
a.npm 安装

npm install qiniu-js

b.引入

const qiniu = require('qiniu-js')
// or
import * as qiniu from 'qiniu-js'

2.使用

<template>
  <div class="upload">
    <div class="uploadbox">
      <div class="uploaddetail cl">
        <div class="left">
          <el-radio v-model="radio" label="0">File</el-radio>
          <div class="img-box _img-box" id="uploadFile" v-if="radio == 0">
            <el-upload
              ref="upload"
              action="http://up-z2.qiniup.com"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :auto-upload="true"
              :limit="1"
              :data="form"
            >
              <el-button
                slot="trigger"
                size="small"
                type="primary"
                class="videobtn"
                ><img src="@/assets/uploadico.png" class="upload-img"
              /></el-button>
            </el-upload>
            <video
              v-if="content"
              :src="urladdress(content)"
              alt=""
              class="videocover"
            ></video>
          </div>
          <div class="img-box2" v-if="radio == 1">
            <img src="@/assets/uploadico.png" class="upload-img" />
          </div>
          <div class="explain cl">
            Upload your file less than 100MB. Only mp4 format is supported.
          </div>
          <ul class="cover">
            <li>Select the cover</li>
            <!-- <li>Add custom image as cover</li> -->
          </ul>
          <div id="choose-box">
            <div class="choose-four-box">
              <img
                v-for="(item, index) in imgurlall"
                :key="index"
                :src="urladdress(item.src)"
                @click="imgClick(index, item.src)"
                :class="imgurlcolor == index ? 'img-border' : ''"
              />
            </div>
            <div class="choose-box"></div>
          </div>
          <div class="or">Or</div>
          <el-radio v-model="radio" label="1">Link</el-radio>
          <el-input
            placeholder="Video Link"
            v-model="content"
            clearable
            class="videoLink"
            :disabled="radio == 1 ? false : true"
          >
          </el-input>
          <div class="hint">Add a video from YouTube or Vimeo.</div>
        </div>
      </div>
      <div class="Publish" @click="submitForm('ruleForm')">Publish</div>
    </div>
  </div>
</template>


<script>
import { urladdress } from "@/js/imgurl";
// 接口引入
import { qiniurequest } from "@/api/en/upload";
// 七牛引入
import * as qiniu from "qiniu-js";
export default {
  data() {
    return {
      radio: "0",
      // 视频地址
      content: "",
      // 七牛的token
      token: "",
      videoUrl: "",
      form: {},
      subscription: "",
      // 获取视频时长的值
      // 视频地址
      timevideourl: "",
      // 视频图片地址
      dataAll: [],
      imgurlall: [],
      ruleForm: {},
      // 封面地址
      cover: "",
      imgurlcolor: "6",
      // 赛事id
      game_id: "",
    };
  },
  methods: {
    contestData() {
      // 获取七牛的token
      qiniurequest().then((res) => {
        if ((res.code = 100000)) {
          this.token = res.data.data;
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.videoUrl = URL.createObjectURL(file.raw);
      console.log(this.videoUrl, "this.videoUrl");
    },
    beforeAvatarUpload(file) {
      const _this = this;
      const fileType = file.type;
      const current = new Date().getTime();
      const key = `video_${current}.mp4`; // key为上传后文件名 必填
      const isLt20M = file.size / 1024 / 1024 < 100; // 算出文件大小
      this.fileSize = file.size; // 存储文件大小
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2,
        concurrentRequestLimit: 1000,
      };
      // this.qiniudata();

      const token = this.token;
      if (!isLt20M) {
        // 这里我们限制文件大小为20M
        this.$message.error("最大只能上传100M!");
        this.$ref.upload.abort();
        return isLt20M;
      }
      if (
        [
          "video/mp4",
          // "video/ogg",
          // "video/flv",
          // "video/avi",
          // "video/wmv",
          // "video/rmvb",
          // "video/mov"
        ].indexOf(file.type) == -1
      ) {
        // this.$message.error("请上传支持的数据格式(mp4,flv,avi,wmv,rmvb,mov)");
        this.$message.error("请上传支持的数据格式(mp4)");
        return false;
      }
      // 获取视频时长
      var url = URL.createObjectURL(file);
      var audioElement = new Audio(url);
      let duration;
      var ele = this.$refs.dur;
      audioElement.addEventListener("loadedmetadata", function (_event) {
        duration = audioElement.duration; //时长为秒,小数,182.36
        // this.$parent.$data.wDuration = parseInt(duration) //注意传递给接口的时长字段类型要与接口接收的字段类型一致,不然无法获取到值
        // console.log(ele.name, "ele.name");
      });
      var observable = qiniu.upload(file, key, token, config);
      var observer = {
        next(res) {
          var { percent } = res.total;
        },
        error(err) {
          console.log(err);
        },
        complete(res) {
          // debugger;
          _this.content = res.key;
          // 得到四个封面图
          var one_times = parseInt(duration / 4);
          var timesAll = null;
          let dataAll = [];
          for (var i = 0; i < 4; i++) {
            timesAll += one_times;
            var src =
              _this.content +
              "?vframe/png/offset/" +
              timesAll +
              "/w/1398/h/852";
            dataAll.push({ src });
          }
          _this.imgurlall = dataAll;
        },
      };
      var subscription = observable.subscribe(observer);
    },
    imgClick: function (data1, data2) {
      this.imgurlcolor = data1;
      this.cover = data2;
    },
    urladdress,
  },
  mounted() {},
  created() {
    this.game_id = this.$route.params.id;
    this.contestData();
  },
};
</script>



<style scoped lang="less">
@import "~@/styles/en/mobile/upload/upload.less";
</style>
<style lang='less'>
</style>

3.效果图

在这里插入图片描述

参考文档

https://developer.qiniu.com/kodo/1283/javascript

https://developer.qiniu.com/dora/1313/video-frame-thumbnails-vframe

https://www.cnblogs.com/dawenyang/p/11381234.html

https://www.jianshu.com/p/e66801df24ca

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中使用七牛云进行上传,需要先在七牛云申请一个空间并获取 Access Key 和 Secret Key,然后安装相关的依赖库。 1. 安装依赖库: ``` npm install qiniu-js vue-qiniu-upload --save ``` 2. 在 Vue 中引入依赖: ``` import QiniuUpload from 'vue-qiniu-upload' import * as qiniu from 'qiniu-js' ``` 3. 在 Vue 组件中使用: ``` <template> <div> <qiniu-upload :domain="domain" :access-key="accessKey" :secret-key="secretKey" :path="path" :size="size" :accept="accept" :before="beforeUpload" :complete="uploadComplete" :error="uploadError" > <button>上传片</button> </qiniu-upload> </div> </template> <script> export default { components: { QiniuUpload }, data () { return { domain: 'your-qiniu-domain', accessKey: 'your-access-key', secretKey: 'your-secret-key', path: '/upload', size: 10 * 1024 * 1024, accept: 'image/*' } }, methods: { beforeUpload (file) { // 可以在这里进行一些上传前的操作,比如片压缩等 }, uploadComplete (res) { // 上传完成后的回调 console.log('上传完成', res) }, uploadError (err) { // 上传失败的回调 console.log('上传失败', err) } } } </script> ``` 以上代码中,`QiniuUpload` 组件是我们刚才引入的依赖库中提供的,通过传入相关参数就可以进行上传了。在 `beforeUpload` 方法中可以对片进行一些处理,比如压缩等操作。`uploadComplete` 和 `uploadError` 分别是上传成功和上传失败后的回调函数,可以进行一些相关的操作。 注意,上传片之前需要在七牛云中进行配置,具体可以参考七牛云的文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值