vue2实现腾讯云cos视频、音频等文件直传完整代码说明

随着网络的告诉发展,人们对于信息的获取方式也不再局限于文字的方式获取更多的是通过图片、视频等方式来获取信息。

这也就意味着企业如果使用自己服务器进行这些大文件的存储和流量成本的增高,于是第三方存储服务应运而生。本篇内容就介绍在前端开发中如何实现不通过后台将视频等大文件直接存储到腾讯云这类第三方存储服务中。

一、安装cos-js-sdk-v5
npm i cos-js-sdk-v5
二、页面中引入并使用

    2.1、单页面引入cos-js-sdk-v5

import COS from 'cos-js-sdk-v5';

    2.2、上传file文件

<input  ref="fileInput" type="file" @change="handleFileChange" />

    2.3、公用方法直传腾讯云COS

async handleFileChange() {
//上传的文件
const file = this.$refs.fileInput.files[0]; // 获取input file选择的文件

let timestamp = Date.parse(new Date());
let date = new Date(timestamp);
let Y = date.getFullYear(); //年
let M = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; //月
let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); //日
let h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); //时
let m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); //分
let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
let tempFormat = file.name.substring(file.name.lastIndexOf(".") + 1);
let filePath = "upload/video/" + Y + M + D + "/" + Y + M + D + h + m + s + "." + tempFormat;
//腾讯云直传
let cos = new COS({
SecretId: '', // 替换为你的SecretId
SecretKey: '', // 替换为你的SecretKey
});
cos.putObject({
Bucket: '',
Region: "",
Key: filePath,
Body: file,
},(err, data) => {
if (err) {
console.error(err);
_this.$refs.fileInput.value = null;
} else {
console.log("data:::", data);
}
}
);
}

参数说明:

    SecretId:SecretId是腾讯云账号的唯一标识符,在腾讯云控制台可见。

    SecretKey:SecretKey仅生成时可见,需妥善保存

    Bucket:腾讯云COS存储桶名称

    Region:设置Bucket所在地域

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!