最新更新时间:2020年03月05日10:53:05
《猛戳-查看我的博客地图-总有你意想不到的惊喜》
本文内容:在微信小程序中接入腾讯云的COS服务,上传图片至腾讯云的实际应用方案
概述
对象存储(Cloud Object Storage,COS)是腾讯云提供的一种存储海量文件的分布式存储服务,用户可通过网络随时存储和查看数据。腾讯云 COS 使所有用户都能使用具备高扩展性、低成本、可靠和安全的数据存储服务。
COS 通过控制台、API、SDK 和工具等多样化方式简单、快速地接入,实现了海量数据存储和管理。通过 COS 可以进行多格式文件的上传、下载和管理。腾讯云提供了直观的 Web 管理界面,同时遍布全国范围的 CDN 节点可以对文件下载进行加速。
实例
- 采用腾讯云方案存储的背景:
项目中上传图片到自己的服务器,已有方案使用过base64和二进制流的形式,base64上传方案前端压力过大性能不好,同时两种方案对自己的服务器写入压力过大,直接原因是自己服务器性能配置不高
- 在项目中接入COS对象,并上传图片
//第一步 获取后端定义好的存储路径
getPicturePath();// /files/pic/2020/3/5
//第二步 获取腾讯云存储对象,证书信息
getCredential(){
http({
url: 'getCredential',
data: {},
method: 'GET'
}).then((res) => {
if (res.code == 100) {
var data = res.data;
this.cosData = data;//存储桶数据
var credentials = data.credentials;//存储桶证书信息
this.credentials = {
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
XCosSecurityToken: credentials.sessionToken,
ExpiredTime: data.expiredTime,
}
}
})
}
//第三步 腾讯云存储对象实例化
let _this = this;
this.cos = new COS({
getAuthorization: function (options, callback) {
callback(_this.credentials);//_this.credentials 存储桶证书信息
}
});
//第四步 向腾讯云上传图片
postObject(tmpFilePath){
let _this = this;
//图片格式 tmpFilePath.substr(tmpFilePath.lastIndexOf('.'));
var filename = "第一步的存储路径" + "32位uuid" + "图片格式";// /files/pic/2020/3/5 + 62dd6722-257f-4602-857d-9579a7239ad2 + .jpg"
this.cos.postObject({
Bucket: this.cosData.bucketName,//存储桶
Region: this.cosData.region,//地域信息
Key: filename,
FilePath: tmpFilePath,
onProgress: function (info) {}
}, function (err, data) {
//如果向腾讯云上传图片失败 不再向自己服务器存储图片路径
if (err){
console.log(err);//uploadFile:fail url not in domain list
return
}
//向自己服务器存储图片路径 data.Location filename
sendFilePathToServer(data.Location);
});
}
- 第四步中回调函数中的data对象
data = {
ETag: "1a8b856cebfc5a366c482a5ae42e8e0f",
Location: "",
statusCode: 200,
headers: {
Connection: "close",
Content-Length: "0",
Date: "Wed, 04 Mar 2020 16:29:34 GMT",
ETag: "1a8b856cebfc5a366c482a5ae42e8e0f",
Location: "http://seal-test.cos.ap-beijing.myqcloud.com/" + "第四步的filename" ,
Server: "tencent-cos",
x-cos-request-id:
"NWU1ZmQ3NmVfNmFiNzJhMDlfMWRkZGVfMTU1ZmYwYg==",
}
}
- uuid
UUID 是 通用唯一识别码(Universally Unique Identifier)的缩写
/**
* 生成uuid 32位 + 4个-
* @return uuid
*/
function uuid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
参考资料
感谢阅读,欢迎评论^-^