Loading [MathJax]/jax/output/HTML-CSS/jax.js
1 Star 0 Fork 0

Mocha/cos-sdk-flutter-plugin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
jordanqin- jordanqin 1.2.0 b30a7a5 8个月前
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

本文介绍 tencentcloud_cos_sdk_plugin 如何快速入门以及 API 介绍。

相关资源

准备工作

  1. 您需要一个纯 Flutter 项目或 Flutter 原生混合项目,这个应用可以是您现有的工程,也可以是您新建的一个空的工程。
  2. Flutter 版本要求:
  sdk: ">=2.15.0 <4.0.0"
  flutter: ">=2.5.0"

第一步:SDK 介绍

tencentcloud_cos_sdk_plugin 目前兼容支持 iOS、Android,是通过 Flutter Plugin 桥接原生 AndroidiOS 的 COS SDK 实现。

第二步:集成 SDK

  1. 运行此命令:
flutter pub add tencentcloud_cos_sdk_plugin
  1. 这将向您的包的 pubspec.yaml 添加这样一行(并运行隐式 flutter pub get)
dependencies:
  tencentcloud_cos_sdk_plugin: ^1.2.0
  1. 在您的 Dart 代码中,您可以使用 import 进行导入,然后开始使用:
import 'package:tencentcloud_cos_sdk_plugin/cos.dart';

关闭腾讯灯塔上报功能

为了持续跟踪和优化 SDK 的质量,给您带来更好的使用体验,我们在 SDK 中引入了 腾讯灯塔 SDK,腾讯灯塔只对 COS 侧的请求性能进行监控,不会上报业务侧数据。 若是想关闭该功能,可以在依赖引入和 import 时将 tencentcloud_cos_sdk_plugin 替换为 tencentcloud_cos_sdk_plugin_nobeacon即可。

第三步:开始使用

!

  • 建议用户 使用临时密钥 调用 SDK,通过临时授权的方式进一步提高 SDK 使用的安全性。申请临时密钥时,请遵循 最小权限指引原则,防止泄漏目标存储桶或对象之外的资源。
  • 如果您一定要使用永久密钥,建议遵循 最小权限指引原则 对永久密钥的权限范围进行限制。

1. 初始化密钥

实现获取临时密钥

实现一个 IFetchCredentials 的类,实现请求临时密钥并返回结果的过程。

import 'dart:convert';
import 'dart:io';

import 'package:tencentcloud_cos_sdk_plugin/fetch_credentials.dart';
import 'package:tencentcloud_cos_sdk_plugin/pigeon.dart';

class FetchCredentials implements IFetchCredentials{
  @override
  Future<SessionQCloudCredentials> fetchSessionCredentials() async {
    // 首先从您的临时密钥服务器获取包含了密钥信息的响应,例如:
    var httpClient = HttpClient();
    try {
      // 临时密钥服务器 url
      var stsUrl = "http://stsservice.com/sts";
      var request = await httpClient.getUrl(Uri.parse(stsUrl));
      var response = await request.close();
      if (response.statusCode == HttpStatus.OK) {
        var json = await response.transform(utf8.decoder).join();
        print(json);

        // 然后解析响应,获取临时密钥信息
        var data = jsonDecode(json);
        // 最后返回临时密钥信息对象
        return SessionQCloudCredentials(
            secretId: data['credentials']['tmpSecretId'],// 临时密钥 SecretId
            secretKey: data['credentials']['tmpSecretKey'],// 临时密钥 SecretKey
            token: data['credentials']['sessionToken'],// 临时密钥 Token
            startTime: data['startTime'],//临时密钥有效起始时间,单位是秒
            expiredTime: data['expiredTime']//临时密钥有效截止时间戳,单位是秒
        );
      } else {
        throw ArgumentError();
      }
    } catch (exception) {
      throw ArgumentError();
    }
  }
}

这里假设类名为 FetchCredentials。初始化一个实例,来给 SDK 提供密钥。

Cos().initWithSessionCredential(FetchCredentials());

实现获取限制范围的临时密钥

该方式可以更精细的控制临时密钥的使用范围,STSCredentialScope中包含了本次请求的action(操作)、region、bucket、prefix, 使用STSCredentialScope可以生成一个限定范围的临时密钥,例如根据prefix生成固定路径文件名的上传临时密钥,实现每个上传文件都有单独的临时密钥。

实现一个 IFetchScopeLimitCredentials 的类,实现请求限制范围的临时密钥并返回结果的过程。

import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:tencentcloud_cos_sdk_plugin/fetch_credentials.dart';
import 'package:tencentcloud_cos_sdk_plugin/pigeon.dart';

class FetchScopeLimitCredentials implements IFetchScopeLimitCredentials{
  @override
  Future<SessionQCloudCredentials> fetchScopeLimitCredentials(List<STSCredentialScope?> stsCredentialScopes) async {
    // 首先从您的临时密钥服务器获取包含了密钥信息的响应,例如:
    var httpClient = HttpClient();
    try {
      // 临时密钥服务器 url,临时密钥生成服务请参考 https://cloud.tencent.com/document/product/436/14048
      // 范围限制的临时密钥服务请参考:https://cloud.tencent.com/document/product/436/31923
      var stsUrl = "https://stsservice.com/sts/scope";
      var request = await httpClient.postUrl(Uri.parse(stsUrl));
      request.headers.contentType = ContentType.json;
      // 将范围实体列表转换为post body中的json
      final body = jsonifyScopes(stsCredentialScopes);
      if (kDebugMode) {
        print(body);
      }
      request.write(body);

      var response = await request.close();
      if (response.statusCode == HttpStatus.OK) {
        var json = await response.transform(utf8.decoder).join();
        if (kDebugMode) {
          print(json);
        }
        // 然后解析响应,获取临时密钥信息
        var data = jsonDecode(json);
        // 最后返回临时密钥信息对象
        return SessionQCloudCredentials(
            secretId: data['credentials']['tmpSecretId'],
            secretKey: data['credentials']['tmpSecretKey'],
            token: data['credentials']['sessionToken'],
            startTime: data['startTime'],
            expiredTime: data['expiredTime']
        );
      } else {
        throw ArgumentError();
      }
    } catch (exception) {
      if (kDebugMode) {
        print(exception);
      }
      throw ArgumentError();
    }
  }

  // 将范围实体列表转换为json
  String jsonifyScopes(List<STSCredentialScope?> scopes) {
    List<Map<String, String?>> scopeList = [];
    for (STSCredentialScope? scope in scopes) {
      if(scope != null) {
        Map<String, String?> scopeMap = {
          'action': scope.action,
          'bucket': scope.bucket,
          'prefix': scope.prefix,
          'region': scope.region,
        };
        scopeList.add(scopeMap);
      }
    }
    return jsonEncode(scopeList);
  }
}

这里假设类名为 FetchScopeLimitCredentials。初始化一个实例,来给 SDK 提供密钥。

Cos().initWithScopeLimitCredential(FetchScopeLimitCredentials());

强制使本地保存的临时密钥失效

该功能可以强制使 COS SDK 已经缓存的临时密钥失效,包括无限制使用范围和限制使用范围的临时密钥,失效后再使用 COS 接口功能时 SDK 会重新向业务临时密钥服务端获取新的临时密钥。 调用方法:

await Cos().forceInvalidationCredential();

使用永久密钥进行本地调试

您可以使用腾讯云的永久密钥来进行开发阶段的本地调试。由于该方式存在泄漏密钥的风险,请务必在上线前替换为临时密钥的方式。

String SECRET_ID = "SECRETID"; //永久密钥 secretId
String SECRET_KEY = "SECRETKEY"; //永久密钥 secretKey

Cos().initWithPlainSecret(SECRET_ID, SECRET_KEY);

2. 注册 COS 服务

// 存储桶所在地域简称,例如广州地区是 ap-guangzhou
String region = "COS_REGION";
// 创建 CosXmlServiceConfig 对象,根据需要修改默认的配置参数
CosXmlServiceConfig serviceConfig = CosXmlServiceConfig(
    region: region,
    isDebuggable: true,
    isHttps: true,
);
// 注册默认 COS Service
Cos().registerDefaultService(serviceConfig);

// 创建 TransferConfig 对象,根据需要修改默认的配置参数
// TransferConfig 可以设置智能分块阈值 默认对大于或等于2M的文件自动进行分块上传,可以通过如下代码修改分块阈值
TransferConfig transferConfig = TransferConfig(
    forceSimpleUpload: false,
    enableVerification: true,
    divisionForUpload: 2097152, // 设置大于等于 2M 的文件进行分块上传
    sliceSizeForUpload: 1048576, //设置默认分块大小为 1M
);
// 注册默认 COS TransferManger
Cos().registerDefaultTransferManger(serviceConfig, transferConfig);

// 也可以通过 registerService 和 registerTransferManger 注册其他实例, 用于后续调用
// 一般用 region 作为注册的key
String newRegion = "NEW_COS_REGION";
Cos().registerService(newRegion, serviceConfig..region = newRegion);
Cos().registerTransferManger(newRegion, serviceConfig..region = newRegion, transferConfig);

参数说明

CosXmlServiceConfig 用于配置 COS 服务,其主要成员说明如下:

参数名称 描述 类型 默认值 支持平台
region 存储桶地域 地域和访问域名 String null Android和iOS
connectionTimeout 连接超时时间(单位是毫秒) Int Android(15000) iOS(30000) Android和iOS
socketTimeout 读写超时时间(单位是毫秒) Int 30000 Android
isHttps 是否使用https协议 Bool true Android和iOS
host 设置除了 GetService 请求外的 host String null Android和iOS
hostFormat 设置 host 的格式化字符串,sdk 会将 bucketbucket{region} 替换为真正的 region
例如将 hostFormat 设置为 bucket.{region}.tencent.com,并且您的存储桶和地域分别为 bucket-1250000000 和 ap-shanghai,那么最终的请求地址为 bucket-1250000000.ap-shanghai.tencent.com
  • 注意,这个设置不会影响 GetService 请求
  • String null Android
    port 设置请求的端口 Int null Android
    isDebuggable 是否是 debug 模式(debug 模式会打印 debug 日志) Bool false Android
    signInUrl 是否将签名放在 URL 中,默认放在 Header 中 Bool false Android
    userAgent ua 拓展参数 String null Android和iOS
    dnsCache 是否开启 DNS 解析缓存,开启后,将 DNS 解析的结果缓存在本地,当系统 DNS 解析失败后,会使用本地缓存的 DNS 结果 Bool true Android
    accelerate 是否使用全球加速域名 Bool false Android和iOS

    TransferConfig 用于配置 COS 上传服务,其主要成员说明如下:

    参数名称 描述 类型 默认值 支持平台
    divisionForUpload 设置启用分块上传的最小对象大小 Int 2097152 Android和iOS
    sliceSizeForUpload 设置分块上传时的分块大小 Int 1048576 Android和iOS
    enableVerification 分片上传时是否整体校验 Bool true Android和iOS
    forceSimpleUpload 是否强制使用简单上传 Bool false Android

    第四步:访问 COS 服务

    上传对象

    SDK 支持上传本地文件、二进制数据。下面以上传本地文件为例:

        // 获取 TransferManager
        CosTransferManger transferManager = Cos().getDefaultTransferManger();
        //CosTransferManger transferManager = Cos().getTransferManger("newRegion");
        // 存储桶名称,由 bucketname-appid 组成,appid 必须填入,可以在 COS 控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
        String bucket = "examplebucket-1250000000";
        String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
        String srcPath = "本地文件的绝对路径"; //本地文件的绝对路径
        //若存在初始化分块上传的 UploadId,则赋值对应的 uploadId 值用于续传;否则,赋值 null
        String? _uploadId;
    
        // 上传成功回调
        successCallBack(result) {
          // todo 上传成功后的逻辑
        }
        //上传失败回调
        failCallBack(clientException, serviceException) {
          // todo 上传失败后的逻辑
          if (clientException != null) {
            print(clientException);
          }
          if (serviceException != null) {
            print(serviceException);
          }
        }
        //上传状态回调, 可以查看任务过程
        stateCallback(state) {
          // todo notify transfer state
        }
        //上传进度回调
        progressCallBack(complete, target) {
          // todo Do something to update progress...
        }
        //初始化分块完成回调
        initMultipleUploadCallback(
            String bucket, String cosKey, String uploadId) {
          //用于下次续传上传的 uploadId
          _uploadId = uploadId;
        }
        //开始上传
        TransferTask transferTask = await transferManager.upload(bucket, cosPath,
            filePath: srcPath,
            uploadId: _uploadId,
            resultListener: ResultListener(successCallBack, failCallBack),
            stateCallback: stateCallback,
            progressCallBack: progressCallBack,
            initMultipleUploadCallback: initMultipleUploadCallback
        );
        //暂停任务
        transferTask.pause();
        //恢复任务
        transferTask.resume();
        //取消任务
        transferTask.cancel();
    

    下载对象

        // 高级下载接口支持断点续传,所以会在下载前先发起 HEAD 请求获取文件信息。
        // 如果您使用的是临时密钥或者使用子账号访问,请确保权限列表中包含 HeadObject 的权限。
    
        // TransferManager 支持断点下载,您只需要保证 bucket、cosPath、savePath
        // 参数一致,SDK 便会从上次已经下载的位置继续下载。
    
        // 获取 TransferManager
        CosTransferManger transferManager = Cos().getDefaultTransferManger();
        //CosTransferManger transferManager = Cos().getTransferManger("newRegion");
        // 存储桶名称,由 bucketname-appid 组成,appid 必须填入,可以在 COS 控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
        String bucket = "examplebucket-1250000000";
        String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
        String downliadPath = "本地文件的绝对路径"; //保存到本地文件的绝对路径
    
        // 下载成功回调
        successCallBack(result) {
          // todo 下载成功后的逻辑
        }
        //下载失败回调
        failCallBack(clientException, serviceException) {
          // todo 下载失败后的逻辑
          if (clientException != null) {
            print(clientException);
          }
          if (serviceException != null) {
            print(serviceException);
          }
        }
        //下载状态回调, 可以查看任务过程
        stateCallback(state) {
          // todo notify transfer state
        }
        //下载进度回调
        progressCallBack(complete, target) {
          // todo Do something to download progress...
        }
        //开始下载
        TransferTask transferTask = await transferManager.download(bucket, cosPath, downliadPath, 
            resultListener: ResultListener(successCallBack, failCallBack),
            stateCallback: stateCallback,
            progressCallBack: progressCallBack
        );
        //暂停任务
        transferTask.pause();
        //恢复任务
        transferTask.resume();
        //取消任务
        transferTask.cancel();
    
    Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

    简介

    cos-sdk-flutter-plugin 展开 收起
    README
    Apache-2.0
    取消

    发行版 (2)

    全部
    7个月前

    贡献者

    全部

    近期动态

    不能加载更多了
    马建仓 AI 助手
    尝试更多
    代码解读
    代码找茬
    代码优化
    1
    https://gitee.com/changleibox/cos-sdk-flutter-plugin.git
    git@gitee.com:changleibox/cos-sdk-flutter-plugin.git
    changleibox
    cos-sdk-flutter-plugin
    cos-sdk-flutter-plugin
    main

    搜索帮助