vue element-ui 上传视频到腾讯云cos-js-sdk-v5(对象储存)

先贴官网文档链接 腾讯云cos-js-sdk-v5
每一步文档都写的很清楚 就是有些太简洁 第一次我是有点蒙
首先安装 npm i cos-js-sdk-v5 --save

utils文件夹里创建一个upload.js

/* 1.获取临时秘钥data 2.初始化 3.判断上传文件的类型 4.判断文件大小 是否需要分片上传*/

import COS from 'cos-js-sdk-v5'
import axios from 'axios'
import { Message } from 'element-ui'

// 上传
export function putObject(file, callback) {
  // console.log(file)
  let file_name = file.name
  let url = 'https://vido-api-2020.4kt.net/admin/v2.tengxun/up_sign' // 秘钥相关信息
  axios.post(url).then((response) => {
    // 后台接口返回 密钥相关信息
    const data = response.data
    var credentials = data && data.credentials
    
    // 获取当前时间戳 可以与文件名拼接 为cos.putObject里的参数Key
    // let uploadFileName = Date.parse(new Date()) 
    
    if (!data || !credentials) return console.error('credentials invalid')
    // 初始化
    var cos = new COS({
      getAuthorization: function (options, callback) {
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          XCosSecurityToken: credentials.sessionToken,
          StartTime: data.startTime,
          ExpiredTime: data.expiredTime,
          expiration: data.expiration,
          requestId: data.requestId,
        })
      },
    })
    // 获取上传文件类型
    let type = file.type.substring(0, 5)
    let size = file.size
    if (type === 'video') {
      // console.log(size / (1024 * 2024))
      if (size / (1024 * 2024) < 50) {
        // console.log('普通上传')
        cos.putObject(
          {
            Bucket: 'course-1300669354', // 存储桶名称
            Region: 'ap-beijing', // 地区
            Key: '/video/' + file_name, // 视频名称
            StorageClass: 'STANDARD',
            Body: file, // 上传文件对象
            onHashProgress: function (progressData) {
              // console.log('校验中', JSON.stringify(progressData))
            },
            onProgress: function (progressData) {
              // console.log('上传中', JSON.stringify(progressData))
            },
          },
          function (err, data) {
            // console.log('1')
            // console.log(err)
            // console.log(data)
            // console.log('999', err, data, data.Location)
            if (err) {
              Message({ message: '文件上传失败,请重新上传', type: 'error' })
            } else {
              let fileUrl = 'http://' + data.Location
              callback(fileUrl, file_name)
            }
          }
        )
      } else {
        // console.log('上传分块')
        cos.sliceUploadFile(
          {
            Bucket: 'course-1300669354' /* 必须 */,
            Region: 'ap-beijing' /* 存储桶所在地域,必须字段 */,
            Key: '/video/' + file_name /* 必须 */,
            Body: file,
            onTaskReady: function (taskId) {
              /* 非必须 */
              // console.log(taskId)
            },
            onHashProgress: function (progressData) {
              /* 非必须 */
              // console.log(JSON.stringify(progressData))
            },
            onProgress: function (progressData) {
              /* 非必须 */
              // console.log(JSON.stringify(progressData))
            },
          },
          function (err, data) {
            // console.log(err)
            // console.log(data)
            if (err) {
              Message({ message: '文件上传失败,请重新上传', type: 'error' })
            } else {
              let fileUrl = 'http://' + data.Location
              callback(fileUrl, file_name)
            }
          }
        )
      }
    } else if (type === 'image') {
      cos.putObject(
        {
          Bucket: 'course-1300669354', // 存储桶名称
          Region: 'ap-beijing', // 地区
          Key: '/img/' + file_name, // 图片名称
          StorageClass: 'STANDARD',
          Body: file, // 上传文件对象
          onHashProgress: function (progressData) {
            // console.log('校验中', JSON.stringify(progressData))
          },
          onProgress: function (progressData) {
            // console.log('上传中', JSON.stringify(progressData))
            // callback(progressData)
          },
        },
        function (err, data) {
          // console.log(err)
          // console.log(data)
          // console.log('999', err, data, data.Location)
          if (err) {
            Message({ message: '文件上传失败,请重新上传', type: 'error' })
          } else {
            let fileUrl = 'http://' + data.Location
            callback(fileUrl, file_name)
          }
        }
      )
    }
  })
}

export function deleteObject(file, callback) {
  let file_name = file.name
  let url = 'https://vido-api-2020.4kt.net/admin/v2.tengxun/up_sign' // 秘钥相关信息
  axios.post(url).then((response) => {
    // 后台接口返回 密钥相关信息
    const data = response.data
    var credentials = data && data.credentials
    let uploadFileName = Date.parse(new Date())
    var cos = new COS({
      getAuthorization: function (options, callback) {
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          XCosSecurityToken: credentials.sessionToken,
          StartTime: data.startTime,
          ExpiredTime: data.expiredTime,
          expiration: data.expiration,
          requestId: data.requestId,
        })
      },
    })
    console.log(file)
    let type = file.type.substring(0, 5)
    if (type === 'video') {
      // console.log('是视频类型')
      cos.deleteObject(
        {
          Bucket: 'course-1300669354' /* 必须 */,
          Region: 'ap-beijing' /* 存储桶所在地域,必须字段 */,
          Key: '/video/' + file.name /* 必须 */,
        },
        function (err, data) {
          // console.log(err)
          // console.log(data)
          if (data) {
            console.log('视频删除成功')
            callback(1)
          }
        }
      )
    } else if (type === 'image') {
      // console.log('是图片类型')
      cos.deleteObject(
        {
          Bucket: 'course-1300669354' /* 必须 */,
          Region: 'ap-beijing' /* 存储桶所在地域,必须字段 */,
          Key: '/img/' + file.name /* 必须 */,
        },
        function (err, data) {
          console.log('图片删除成功')
          // console.log(err)
          // console.log(data)
          if (data) {
            callback(1)
          }
        }
      )
    }
  })
}

export default {
  putObject,
  deleteObject,
}


uplode.vue

<template>
  <div class="Upfile">
	<el-upload
		ref="upload"
		class="upload-demo"
		:file-list="fileList"
		action="#"
		:accept="video/*"
		:http-request="getTmp_secret_keys"
		:before-upload="beforeAvatarUpload"
		:on-remove="handleRemove"
		:on-change="handleChange"
	 >
	 	<el-button size="small" type="primary" plain>点击上传el-button>
	el-upload>
	<canvas id="mycanvas" style="display: none">canvas>
  div>
template>

<script>
import { putObject, deleteObject } from '@/utils/upload'
export default {
	data() {
		return{
			uploadFile:'',
        	fileList: [],
			form: {
				img: '',
				video: ''
			},
			img_file: ''
		}
	},
	methods: {
		beforeAvatarUpload(file) {
		  // console.log(file)
		  this.uploadFile = file
		},
		// 上传文件
		getTmp_secret_keys() {
		  // console.log(this.uploadFile)
		  let files = putObject(this.uploadFile, (res) => {
		    this.form.video = res
		    // console.log(res)
		    // 当上传文件为视频时 用视频第一帧做封面图片 若是图片则不需要以下内容
		    // 用视频第一帧做封面图片
		    nextTick(() => {
	            const video = document.getElementById('video')
	            video.src = url
	            var canvas = document.getElementById('mycanvas')
	            let ctx = canvas.getContext('2d')
	            video.crossOrigin = 'anonymous'
	            video.currentTime = 1
	            video.oncanplay = () => {
	              canvas.width = video.clientWidth
	              canvas.height = video.clientHeight //获取视频高度
	              // 利用canvas对象方法绘图
	              ctx.drawImage(video, 0, 0, video.clientWidth, video.clientHeight)
	              // 转换成base64形式
	              let imgsrc = canvas.toDataURL('image/png') // 截取后的视频封面
	              this.img_file = this.convertBase64UrlToBlob(imgsrc, name)
	              this.UploadCover(this.img_file)
	              // console.log(imgsrc)
	            }
	          })
		  })
		},
		convertBase64UrlToBlob(urlData, name) {
	        var bytes = window.atob(urlData.split(',')[1]) //去掉url的头,并转换为byte
	        //处理异常,将ascii码小于0的转换为大于0
	        var ab = new ArrayBuffer(bytes.length)
	        var ia = new Uint8Array(ab)
	        for (var i = 0; i < bytes.length; i++) {
	          ia[i] = bytes.charCodeAt(i)
	        }
	        let url = new Blob([ab], { type: 'image/png' })
	        url.name = name + '.png'
	        return url
	      },
		UploadCover(file) {
			//上传第一帧图片到腾讯云
	        // console.log(file)
	        let files = this.putObject(file, (url, name) => {
	          // console.log(url)
	        })
	      },
		handleChange(file, fileList) {
		  // console.log(file)
		  // console.log(fileList)
		  fileList.forEach((info) => {
		    if (file.uid != info.uid) {
		      this.deletefile(info.raw)
		    }
		  })
		  if (fileList.length > 0) {
		    this.fileList = [fileList[fileList.length - 1]]
		  }
		},
		handleRemove(file, fileList) {
		  // 点击删除时
		  // console.log(file.raw)
		  this.deletefile(file.raw)
		},
		deletefile(file) {
		  let files = deleteObject(file, (res) => {
		    if (res === 1) {
		      this.form.video = ''
		    }
		  })
		},
	}
  }
script>

应该能看明白吧 最后根据自己的需要改改

你可能感兴趣的:(腾讯云,vue,vue.js)