腾讯云对象存储使用

快速使用

1.注册腾讯云

2.进入对象存储-->存储桶列表-->创建存储桶

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

 

原文地址:https://www.cnblogs.com/Deaseyy/p/13364032.html