官网:https://cloud.tencent.com/document/product/436/11459
参考:https://blog.csdn.net/qq_40146880/article/details/102829629
一、下载SDK并引入
地址:https://cos-sdk-archive-1253960454.file.myqcloud.com/cos-js-sdk-v5/latest/cos-js-sdk-v5.zip?_ga=1.114550148.286138921.1586252253
(可前往上面官网下载)
<script src="./sdk/cos-js-sdk-v5.min.js"></script>
二、封装上传,cos.js
export default new (class {
constructor() {}
_cos(obj) {
return new COS({
getAuthorization: function(options, callback) {
callback({
TmpSecretId: obj.credentials.tmpSecretId,
TmpSecretKey: obj.credentials.tmpSecretKey,
XCosSecurityToken: obj.credentials.sessionToken,
StartTime: obj.startTime, // 时间戳,单位秒,如:1580000000
ExpiredTime: obj.expiredTime, // 时间戳,单位秒,如:1580000000,SDK 在 ExpiredTime 时间前,不会再次调用 getAuthorization
});
}
});
}
/**
* 文件直传
* @param {Object} obj Bucket、Region...,接口返回
* @returns err || data
*/
putObject(obj,file,callback) {
return new Promise((resolve, reject) => {
this._cos(obj).putObject(
{
Bucket: obj.bucket, /* 必须 */
Region: obj.region, /* 存储桶所在地域,必须字段 */
Key: obj.prefix + `${this.randomSign(3)}.${file.name.split('.')[1]}`, /* 必须 */
Body: file, // 上传文件对象
},
(err, data) => {
callback(err,data)
}
);
});
}
/**
* 文件分块上传
* @param {Object} obj Bucket、Region...,接口返回
* @returns err || data
*/
sliceUploadFile(obj,file,callback) {
return new Promise((resolve, reject) => {
this._cos(obj).sliceUploadFile(
{
Bucket: obj.bucket,
Region: obj.region,
Key: obj.prefix + `${this.randomSign(3)}.${file.name.split('.')[1]}`,
Body: file,
onTaskReady: function(taskId) {
/* 执行队列taskId */
console.log('taskId:', taskId);
},
onProgress: progressData => {
/* 非必须 */
var percent = parseInt(progressData.percent * 10000) / 100;
var speed = parseInt((progressData.speed / 1024 / 1024) * 100) / 100;
console.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;');
this.loading('进度:' + parseInt(percent) + '%');
}
},
(err, data) => {
callback(err,data)
}
);
});
}
randomSign(len) {
return `${this.random_string(len)}-${parseInt(Math.floor(Math.random() * Date.now()) / 1000)}`;
}
random_string(len) {
//获取随机名
len = len || 32;
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz';
let maxPos = chars.length;
let pwd = '';
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
loading(text) {
try {
console.log(text);
} catch (error) {
console.log(error);
}
}
})();
三、使用
<!--vue-->
<input @change="handleChange" accept="image/*" type="file" name="" id="" />
import cos from '@/utils/cos'
// 请求数据
$.get('http://xxxxxxx', null, function (res) {
// res:{
// code: 1,
// data: {
// bucket: "dev....51007710",
// credentials:
// {
// sessionToken: "GXpM....7N5Asg",
// tmpSecretId: "AKIDF....jB3mQ2",
// tmpSecretKey: "pnof....9qew8="
// },
// domain: "dev....myqcloud.com",
// expiration: "2020-12-24T06:46:10Z",
// expiredTime: 1608792370,
// prefix: "post/..../u/1/",
// region: "ap-chengdu",
// requestId: "cbc6....e080",
// startTime: 1608788770
// },
// msg: ""
// }
if (res.code == 1 && res.data) {
cos._cos(res.data)
} else{
// error
}
});
// 上传
handleChange(e) {
// 这里的this.tx_data为上一步请求接口拿到的数据
var _this = this
if(this.tx_data){
cos.putObject(this.tx_data,e.target.files[0],(error,data)=>{
if(error){
this.$message.error('上传失败')
}else{
this.$message.success('上传成功')
let url = 'https://'+ data.Location
// ...
}
})
}else{
// error
}
}