最新更新時間: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;
}
參考資料
感謝閱讀,歡迎評論^-^