sdk: ">=2.15.0 <4.0.0"flutter: ">=2.5.0"
flutter pub add tencentcloud_cos_sdk_plugin
dependencies:tencentcloud_cos_sdk_plugin: 1.2.6
import 'package:tencentcloud_cos_sdk_plugin/cos.dart';
// Obtain temporary keys (controlled at the business layer)String tmpSecretId = "SECRETID"; // Temporary key SecretIdString tmpSecretKey = "SECRETKEY"; // Temporary key SecretKeyString sessionToken = "SESSIONTOKEN"; // Temporary key Tokenint expiredTime = 1556183496;//Expiration timestamp of the temporary key, in seconds// It is recommended to return the server time as the signature start time to prevent request expiration due to excessive local time deviation on the user's deviceint startTime = 1556182000; // Start time of the temporary key's validity, in secondsSessionQCloudCredentials sessionQCloudCredentials = SessionQCloudCredentials(secretId: tmpSecretId,secretKey: tmpSecretKey,token: sessionToken,startTime: startTime,expiredTime: expiredTime);// Subsequently, pass sessionQCloudCredentials to specific COS operation methods
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';// Implement aIFetchCredentialsclass to handle the process of requesting temporary keys and returning the results.class FetchCredentials implements IFetchCredentials{@overrideFuture<SessionQCloudCredentials> fetchSessionCredentials() async {// First, obtain the response containing key information from your temporary key server, for example:var httpClient = HttpClient();try {// url for the temporary key server. For the temporary key generation service, see https://www.tencentcloud.com/document/product/436/14048var 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);// Then parse the response to obtain temporary key informationvar data = jsonDecode(json);// Finally, return the temporary key information objectreturn SessionQCloudCredentials(secretId: data['credentials']['tmpSecretId'], // Temporary key SecretIdsecretKey: data['credentials']['tmpSecretKey'], // Temporary key SecretKeytoken: data['credentials']['sessionToken'], // Temporary key TokenstartTime: data['startTime'], // Temporary key validity start time, in secondsexpiredTime: data['expiredTime']//Expiration timestamp of the temporary key, in seconds);} else {throw ArgumentError();}} catch (exception) {throw ArgumentError();}}}
FetchCredentials. Initialize an instance to provide credentials to the SDK.await Cos().initWithSessionCredential(FetchCredentials());
String SECRET_ID = "SECRETID"; // User's SecretId. It is recommended to use a sub-account key; authorization follows the principle of least privilege to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1String SECRET_KEY = "SECRETKEY"; // User's SecretKey. It is recommended to use a sub-account key; authorization follows the principle of least privilege to reduce usage risks. For obtaining sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1await Cos().initWithPlainSecret(SECRET_ID, SECRET_KEY);
// The abbreviation for the bucket region, such as ap-guangzhou for GuangzhouString region = "COS_REGION";// Create a CosXmlServiceConfig object and modify the default configuration parameters as neededCosXmlServiceConfig serviceConfig = CosXmlServiceConfig(region: region,isDebuggable: true,isHttps: true,);// Register the default COS Serviceawait Cos().registerDefaultService(serviceConfig);// Create a TransferConfig object and modify the default configuration parameters as needed// TransferConfig allows you to set the intelligent chunking threshold. By default, files larger than or equal to 2MB are automatically uploaded in chunks. You can modify the chunking threshold with the following code.TransferConfig transferConfig = TransferConfig(forceSimpleUpload: false,enableVerification: true,divisionForUpload: 2097152, // Set files larger than or equal to 2MB to be uploaded in chunkssliceSizeForUpload: 1048576, // Set the default chunk size to 1MB);// Register the default COS TransferMangerawait Cos().registerDefaultTransferManger(serviceConfig, transferConfig);// You can also register other instances using registerService and registerTransferManger for subsequent calls.// Generally, region is used as the registration keyString newRegion = "NEW_COS_REGION";await Cos().registerService(newRegion, serviceConfig..region = newRegion);await Cos().registerTransferManger(newRegion, serviceConfig..region = newRegion, transferConfig);
Parameter Name | Description | Type | Default Value | Supported Platforms | Required |
region | The region of the bucket. For details, see Regions and Access Domains | String | null | Android and iOS | Yes |
isDebuggable | whether it is in debug mode (debug mode prints debug logs) | Bool | false | Android | No |
isHttps | Whether to use the https protocol | Bool | true | Android and iOS | No |
connectionTimeout | Connection timeout time (in milliseconds) | Int | Android(15000) iOS(30000) | Android and iOS | No |
socketTimeout | Read/write timeout time (in milliseconds) | Int | 30000 | Android | No |
host | Set the host for all requests except GetService. | String | null | Android and iOS | No |
hostFormat | Set the format string for the host. The SDK will replace ${bucket} with the actual bucket and ${region} with the actual region. For example, set hostFormat to ${bucket}.${region}.tencent.com, and your bucket and region are respectively bucket-1250000000 and ap-shanghai, then the final request address is bucket-1250000000.ap-shanghai.tencent.comNote: This setting does not affect GetService requests. | String | null | Android | No |
port | Set the request port. | Int | null | Android | No |
signInUrl | Whether to place the signature in the URL, which is placed in the Header by default. | Bool | false | Android | No |
userAgent | ua extension parameters | String | null | Android and iOS | No |
dnsCache | Whether to enable DNS resolution caching. When DNS resolution caching is enabled, the DNS resolution results are cached locally. If the system DNS resolution fails, the locally cached DNS results will be used. | Bool | true | Android | No |
accelerate | Whether to use Global Accelerator domain names. | Bool | false | Android and iOS | No |
Parameter Name | Description | Type | Default Value | Supported Platforms | Required |
forceSimpleUpload | Whether to force the use of simple upload. | Bool | false | Android | No |
enableVerification | Whether to verify the integrity during multipart upload. | Bool | true | Android and iOS | No |
divisionForUpload | Set the minimum object size to enable chunked upload. | Int | 2097152 | Android and iOS | No |
sliceSizeForUpload | Set the part size for chunked upload. | Int | 1048576 | Android and iOS | No |
// Obtain the TransferManagerCosTransferManger transferManager = Cos().getDefaultTransferManger();//CosTransferManger transferManager = Cos().getTransferManger("newRegion");// Bucket name in the format of bucketname-appid, where appid must be included. You can view the bucket name in the COS console: https://console.tencentcloud.com/cos5/bucketString bucket = "examplebucket-1250000000";String cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object keyString srcPath = "absolute path of the local file"; // absolute path of the local file// If an UploadId for an initialized multipart upload exists, assign its value to uploadId for resuming; otherwise, assign nullString? _uploadId;// Upload success callbacksuccessCallBack(Map<String?, String?>? header, CosXmlResult? result) {// todo Upload success follow-up logic}// Upload failure callbackfailCallBack(clientException, serviceException) {// todo Upload failure follow-up logicif (clientException != null) {print(clientException);}if (serviceException != null) {print(serviceException);}}// Upload status callback, which allows you to view the task progressstateCallback(state) {// todo notify transfer state}// Upload progress callbackprogressCallBack(complete, target) {// todo Do something to update progress...}// Initialization chunk complete callbackinitMultipleUploadCallback(String bucket, String cosKey, String uploadId) {// Used to resume the upload next time, uploadId_uploadId = uploadId;}// Start uploadTransferTask transferTask = await transferManager.upload(bucket, cosPath,filePath: srcPath,uploadId: _uploadId,resultListener: ResultListener(successCallBack, failCallBack),stateCallback: stateCallback,progressCallBack: progressCallBack,initMultipleUploadCallback: initMultipleUploadCallback,// Configure a single-use temporary key here; if not using the single-use temporary key method, do not pass this parametersessionCredentials: sessionQCloudCredentials);// Pause task//transferTask.pause();// Resume task//transferTask.resume();// Cancel task//transferTask.cancel();
// The advanced download API supports resuming from breakpoints, so it initiates a HEAD request to obtain file information before downloading.// If you are using a temporary key or accessing with a sub-account, ensure that the permission list includes the HeadObject permission.// TransferManager supports resuming downloads from breakpoints; you only need to ensure the bucket, cosPath, and savePath// If the parameters are consistent, the SDK will resume downloading from the last position.// Obtain the TransferManagerCosTransferManger transferManager = Cos().getDefaultTransferManger();//CosTransferManger transferManager = Cos().getTransferManger("newRegion");// Bucket name in the format of bucketname-appid, where appid must be included. You can view the bucket name in the COS console: https://console.tencentcloud.com/cos5/bucketString bucket = "examplebucket-1250000000";String cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object keyString downloadPath = "absolute path of the local file"; // absolute path to save the local file// Download success callbacksuccessCallBack(Map<String?, String?>? header, CosXmlResult? result) {// todo Download success follow-up logic}// Download failure callbackfailCallBack(clientException, serviceException) {// todo Download failure follow-up logicif (clientException != null) {print(clientException);}if (serviceException != null) {print(serviceException);}}// Download status callback, which allows you to view the task progressstateCallback(state) {// todo notify transfer state}// Download progress callbackprogressCallBack(complete, target) {// todo Do something to download progress...}// Start downloadTransferTask transferTask = await transferManager.download(bucket, cosPath, downloadPath,resultListener: ResultListener(successCallBack, failCallBack),stateCallback: stateCallback,progressCallBack: progressCallBack,// Configure a single-use temporary key here; if not using the single-use temporary key method, do not pass this parametersessionCredentials: sessionQCloudCredentials);// Pause task//transferTask.pause();// Resume task//transferTask.resume();// Cancel task//transferTask.cancel();
Feedback