1.注冊騰訊雲
3.查看右上角sdk文檔,根據文檔走下來
1.安裝sdk
手動安裝:
直接拷貝js內容到項目目錄utils下命名cos-wx-sdk-v5.js
npm安裝:
npm install cos-wx-sdk-v5
2.小程序中引入
var COS = require('cos-wx-sdk-v5'); // 填寫具體絕對路徑
3.開始使用
線上產環境需微信公眾平台配置后台域名訪問白名單,選擇【開發】>【開發設置】>【服務器域名】,配置域名白名單。
4.創建一個 COS SDK 實例,COS SDK 支持以下幾種格式創建:
格式一(推薦):后端通過獲取臨時密鑰給到前端,前端計算簽名。
1 var cos = new COS({ 2 // 必選參數 3 getAuthorization: function (options, callback) { 4 // 服務端 JS 和 PHP 示例:https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/ 5 // 服務端其他語言參考 COS STS SDK :https://github.com/tencentyun/qcloud-cos-sts-sdk 6 // STS 詳細文檔指引看:https://cloud.tencent.com/document/product/436/14048 7 wx.request({ 8 // url這里填寫你后端生成臨時密鑰的api地址 9 url: 'https://example.com/server/sts.php', 10 data: { 11 // 可從 options 取需要的參數 12 }, 13 success: function (result) { 14 var data = result.data; 15 var credentials = data && data.credentials; 16 if (!data || !credentials) return 17 console.error('credentials invalid'); 18 callback({ 19 TmpSecretId: credentials.tmpSecretId, 20 TmpSecretKey: credentials.tmpSecretKey, 21 XCosSecurityToken: credentials.sessionToken, 22 // 建議返回服務器時間作為簽名的開始時間,避免用戶瀏覽器本地時間偏差過大導致簽名錯誤 23 StartTime: data.startTime, // 時間戳,單位秒,如:1580000000 24 ExpiredTime: data.expiredTime, // 時間戳,單位秒,如:1580000900 25 }); 26 } 27 }); 28 } 29 });
后端生成臨時密鑰:
接口寫好后,將生成密鑰的地址填到上面的url中即可
1.獲取SDK
pip install -U qcloud-python-sts
2.寫接口
1 import json 2 import os 3 from sts.sts import Sts 4 5 class CredentialView(APIView): 6 def get(sef,request,*args,**kwargs): 7 config = { 8 # 臨時密鑰有效時長,單位是秒 9 'duration_seconds': 1800, 10 'secret_id': 固定secret_id, 11 'secret_key': 固定密鑰, 12 # 設置網絡代理 13 # 'proxy': { 14 # 'http': 'xx', 15 # 'https': 'xx' 16 # }, 17 # 換成你的 bucket(存儲桶) 18 'bucket': 'example-1253653367', 19 # 換成 bucket 所在地區 20 'region': 'ap-guangzhou', 21 # 這里改成允許的路徑前綴,可以根據自己網站的用戶登錄態判斷允許上傳的具體路徑 22 # 例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全風險, 請謹慎評估使用) 23 'allow_prefix': 'exampleobject', 24 # 密鑰的權限列表。簡單上傳和分片需要以下的權限,其他權限列表請看 https://cloud.tencent.com/document/product/436/31923 25 'allow_actions': [ 26 # 簡單上傳 27 'name/cos:PutObject', 28 'name/cos:PostObject', 29 # 分片上傳 30 'name/cos:InitiateMultipartUpload', 31 'name/cos:ListMultipartUploads', 32 'name/cos:ListParts', 33 'name/cos:UploadPart', 34 'name/cos:CompleteMultipartUpload' 35 ], 36 } 37 38 sts = Sts(config) 39 response = sts.get_credential() 40 return Response(response)
格式四:(不推薦):前端使用固定密鑰計算簽名,該格式適用於前端調試,若使用此格式,請避免泄露密鑰
1 var cos = new COS({ 2 SecretId: 'xxxxx', 3 SecretKey: 'xxxxx', 4 });
完整代碼使用示例
小程序端:
這里使用格式1創建COS實例:
1 // 點擊上傳 2 uploadImage() { 3 // // 格式四:使用真實密鑰,適合測試;不推薦,避免泄露密鑰 4 // var cos = new COS({ 5 // SecretId: 'xxxxx', 6 // SecretKey: 'xxxxx', 7 // }); 8 var cos = new COS({ 9 getAuthorization: function (options, callback) { 10 wx.request({ 11 url: 'http://127.0.0.1:8000/api/credential', 12 data: { 13 // 可從options中取需要的參數 14 }, 15 success: function (result) { 16 var data = result.data; 17 var credentials = data && data.credentials; 18 callback({ 19 TmpSecretId: credentials.tmpSecretId, 20 TmpSecretKey: credentials.tmpSecretKey, 21 XCosSecurityToken: credentials.sessionToken, 22 // 建議返回服務器時間作為簽名的開始時間,避免用戶瀏覽器本地時間偏差過大導致簽名錯誤 23 StartTime: data.startTime, // 時間戳,單位秒,如:1580000000 24 ExpiredTime: data.expiredTime, // 時間戳,單位秒,如:1580000900 25 }); 26 } 27 }); 28 } 29 }); 30 for (var index in this.data.imageList) { 31 var filePath = this.data.imageList[index] 32 cos.postObject({ 33 Bucket: 'auction-1302698597', 34 Region: 'ap-shenzhen-fsi', 35 Key: curr_time + index + '.png', 36 FilePath: filePath, 37 // 上傳進度條 38 onProgress: function (info) { 39 console.log('上傳進度條:', JSON.stringify(info)); 40 } 41 }, function (err, data) { 42 // 上傳成功后執行 43 // console.log('上傳之后返回的值:', data.Location); // Location 圖片對象地址(可直接訪問),然后保存地址到數據庫即可 44 wx.request({ 45 url: 'http://127.0.0.1:8000/api/photosView', 46 method: 'POST', 47 data: { 48 img_url: data.Location 49 }, 50 success(res) { 51 // console.log(res.data) 52 Notify({ 53 type: 'success', 54 message: res.data.msg 55 }); 56 } 57 }) 58 }); 59 } 60 },
后端生成臨時密鑰:
api地址:http://127.0.0.1:8000/api/photosView
1 from sts.sts import Sts 2 from django.conf import settings 3 4 class CredentialView(APIView): 5 def get(self,request,*args,**kwargs): 6 config = { 7 # 臨時密鑰有效時長,單位是秒 8 'duration_seconds': 1800, 9 'secret_id': settings.SECRETID, 10 'secret_key': settings.SECRETKEY, 11 # 換成你的 bucket(存儲桶) 12 'bucket': 'auction-1302698597', 13 # 換成 bucket 所在地區 14 'region': 'ap-shenzhen-fsi', 15 # 這里改成允許的路徑前綴,可以根據自己網站的用戶登錄態判斷允許上傳的具體路徑 16 # 例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全風險, 請謹慎評估使用) 17 'allow_prefix': '*', 18 # 密鑰的權限列表。簡單上傳和分片需要以下的權限,其他權限列表請看 https://cloud.tencent.com/document/product/436/31923 19 'allow_actions': [ 20 # 簡單上傳 21 'name/cos:PostObject', 22 ], 23 } 24 25 sts = Sts(config) 26 response = sts.get_credential() 27 return Response(response)
刪除雲存儲對象
removeImage(e) { // 判斷是否正在上傳,如果正在上傳就終止上傳,已傳成功則刪除線上圖片 // 刪除圖片 終止 or 刪除 var index = e.detail.index var item = this.data.imgList[index] if(item.percent == 100) { // 使用上面創建的cos對象 cos.deleteObject({ Bucket: 'auction-1302698597', Region: 'ap-shenzhen-fsi', Key: item.key, }, (err, data) => { if (err) { wx.showToast({ title: '刪除失敗', icon: 'none' }) } else { // 同時刪除頁面顯示 let arr = this.data.imgList arr.splice(index, 1) this.setData({ imgList: arr }) } }) } },
基本使用就是這樣,需要更詳細文檔請看官方:https://cloud.tencent.com/document/product/436/31953