ohpm install @tencentcloud/cos
"dependencies": {..."@tencentcloud/cos":"1.2.1"}
..."requestPermissions":[ { "name" : "ohos.permission.INTERNET",... } ]...
import { QCloudCredential } from '@tencentcloud/cos';// Obtain temporary keys (controlled by the business layer)let credential : QCloudCredential= new QCloudCredential();credential.secretID = "secretID";credential.secretKey = "secretKey";credential.token = "token";// Both startDate and expirationDate are of type Date, constructed here using a millisecond timestampcredential.startDate = new Date();credential.expirationDate = new Date();
import { CredentialCallBack, QCloudCredential } from '@tencentcloud/cos';export class Credential {/*** Obtain STS temporary keys*/public static sessionCredential: CredentialCallBack = (request)=>{return new Promise((resolve, reject) => {// First, obtain a response containing key information from your temporary key serverlet httpRequest = http.createHttp();httpRequest.request(// Please replace it with the specific sts temporary key acquisition service url"http://127.0.0.1/sts",{ method: http.RequestMethod.GET },(err: BusinessError, data: http.HttpResponse) => {if (!err) {const stsSessionQCloudCredentials: StsSessionQCloudCredentials = JSON.parse(data.result.toString());let credential : QCloudCredential= new QCloudCredential();credential.secretID = stsSessionQCloudCredentials.credentials.tmpSecretId;credential.secretKey = stsSessionQCloudCredentials.credentials.tmpSecretKey;credential.token = stsSessionQCloudCredentials.credentials.sessionToken;// It is recommended to use the server time as the signature start time to avoid request expiration caused by significant deviations in the user's local device time.// Both startDate and expirationDate are of type Date, constructed here using a millisecond timestamp,// The timestamp in the sts response is usually in seconds, so it needs to be multiplied by 1000. If your temporary key service returns timestamps in milliseconds, no multiplication by 1000 is requiredcredential.startDate = new Date(stsSessionQCloudCredentials.startTime * 1000);credential.expirationDate = new Date(stsSessionQCloudCredentials.expiredTime * 1000);httpRequest.destroy();// Finally, return the temporary key information objectresolve(credential);} else {httpRequest.destroy();reject(err);}});})}}/*** Temporary Key Entity Definition*/export class StsSessionQCloudCredentials{credentials: StsCredentials;startTime: number;expiredTime: number;constructor(credentials: StsCredentials, startTime: number, expiredTime: number) {this.credentials = credentials;this.startTime = startTime;this.expiredTime = expiredTime;}}export class StsCredentials{tmpSecretId: string;tmpSecretKey: string;sessionToken: string;constructor(tmpSecretId: string, tmpSecretKey: string, sessionToken: string) {this.tmpSecretId = tmpSecretId;this.tmpSecretKey = tmpSecretKey;this.sessionToken = sessionToken;}}
// Define the server-side signature callbacklet selfSignCallBack = async (request)=>{// First, obtain a response containing signature information from your serverlet httpRequest = http.createHttp();httpRequest.request(// Please replace it with the specific signature acquisition service url"http://127.0.0.1/sign",{ method: http.RequestMethod.GET },(err: BusinessError, data: http.HttpResponse) => {if (!err) {// Obtain the signature informationlet signData: object = JSON.parse(data.result.toString());// Set the signature header for the requestrequest.addHeader(HttpHeader.AUTHORIZATION, signData['authorization'])if(signData['securityToken']){request.addHeader("x-cos-security-token", signData['securityToken'])}httpRequest.destroy();} else {httpRequest.destroy();}});}
// Obtain signature data (controlled by the business layer) let authorization: string = "authorization"; let token: string = "token"; let tokenName: string = "x-cos-security-token";
import { CredentialCallBack, QCloudCredential } from '@tencentcloud/cos';export class Credential { /** * Obtain fixed keys. Only used during testing. */ public static constCredential: CredentialCallBack = (request)=>{ return new Promise((resolve, reject) => { let credential : QCloudCredential= new QCloudCredential();// User's SecretId. It is recommended to use a sub-account key, with authorization following the least privilege guidelines to reduce usage risks. Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1 credential.secretID = "SECRETID";// User's SecretKey. It is recommended to use a sub-account key, with authorization following the least privilege guidelines to reduce usage risks. Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1 credential.secretKey = "SECRETKEY"; resolve(credential); }) } }
import { CosXmlBaseService, CosXmlServiceConfig } from '@tencentcloud/cos';// Service configurationlet cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");// Initialize the default ServiceCosXmlBaseService.initDefaultService(this.context.getApplicationContext(),cosXmlServiceConfig// You can omit the temporary key callback)
import { CosXmlBaseService, PutObjectRequest, UploadTask } from '@tencentcloud/cos';// Any CosXmlRequest supports this method, for example, upload PutObjectRequest, download GetObjectRequest, delete DeleteObjectRequest, etc.// The following uses upload as an examplelet putRequest = new PutObjectRequest("examplebucket-1250000000", "exampleobject.txt", "Local file path");// credential is the single-operation temporary key obtained in the first step "Initialize Key"putRequest.credential = credential;let task: UploadTask = CosXmlBaseService.default().upload(putRequest);task.start();
import { CosXmlBaseService, CosXmlServiceConfig } from '@tencentcloud/cos';// Service configurationlet cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");// Initialize the default ServiceCosXmlBaseService.initDefaultService(this.context.getApplicationContext(),cosXmlServiceConfig,// The temporary key callback obtained in the first step "Initialize Key"Credential.sessionCredential)
import { CosXmlBaseService, CosXmlServiceConfig } from '@tencentcloud/cos';// Service configurationlet cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");// Initialize the default ServiceCosXmlBaseService.initDefaultService(this.context.getApplicationContext(),cosXmlServiceConfig)// The server-side signature callback obtained in the first step "Initialize Key"CosXmlBaseService.default().setSelfSignCallBack(selfSignCallBack);
import { CosXmlBaseService, PutObjectRequest, UploadTask } from '@tencentcloud/cos';// Any CosXmlRequest supports this method, for example, upload PutObjectRequest, download GetObjectRequest, delete DeleteObjectRequest, etc.// The following uses upload as an examplelet putRequest = new PutObjectRequest("examplebucket-1250000000", "exampleobject.txt", "Local file path");// authorization, token, and tokenName are the single-signature information obtained in the first step "Initialize Key"putRequest.setSign(authorization, stoken, tokenName);let task: UploadTask = CosXmlBaseService.default().upload(putRequest);task.start();
// Service configurationlet cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");// Initialize the default ServiceCosXmlBaseService.initDefaultService( this.context.getApplicationContext(), cosXmlServiceConfig,// The fixed key callback obtained in the first step "Initialize Key" Credential.constCredential )
Parameter Name | Description | Type | Default Value | Required or Not |
region | Bucket region. For details, see Regions and Access Domains | string | None. | No (or host) |
protocol | Network protocol: https, http | string | https | No |
connectTimeout | Connection timeout (unit: ms) | number | 15 * 1000 | No |
readTimeout | Read timeout (unit: ms) | number | 30 * 1000 | No |
host | Custom domain. The sdk will replace ${bucket} with the actual bucket and ${region} with the actual region. For example: if you set the host to ${bucket}.${region}.tencent.com, and your bucket and region are bucket-1250000000 and ap-shanghai respectively, then the final request address will be bucket-1250000000.ap-shanghai.tencent.com | string | ${bucket}.cos.${region}.myqcloud.com | No (or region) |
port | Set the request port. | number | None. | No |
headers | Set common header. | Map<string, string> | None. | No |
noSignHeaderKeys | Set unsigned header. | Set<string> | None. | No |
uploadMaxConcurrentCount | Concurrent upload tasks | number | 4 | No |
downloadMaxConcurrentCount | Concurrent download tasks | number | 4 | No |
maxRetryCount | Maximum retry times | number | 3 | No |
retrySleep | Retry interval, unit: ms | number | 1000 | No |
dnsConfiguration | Specify DNS-related configurations, including custom DNS rules and the option to use DNS over HTTPS. For details, see rcp.DnsConfiguration | rcp.DnsConfiguration | None. | No |
{"version": "2.0","statement": [{"action": [//head operation"name/cos:HeadObject",//Simple upload operation"name/cos:PutObject",//Multipart upload: Initializing multipart upload operations"name/cos:InitiateMultipartUpload",//Multipart upload: Listing uploaded parts"name/cos:ListParts",//Multipart upload: Uploading parts operation"name/cos:UploadPart",//Multipart upload: Completing all multipart upload operations"name/cos:CompleteMultipartUpload",//Canceling multipart upload operations"name/cos:AbortMultipartUpload"],"effect": "allow","resource": ["qcs::cos:ap-beijing:uid/1250000000:examplebucket-1250000000/doc/*"]}]}
import { CosXmlBaseService, HttpProgress, PutObjectRequest, UploadTask, TransferConfig, CosError } from '@tencentcloud/cos';import { CosXmlUploadTaskResult } from '@tencentcloud/cos/src/main/ets/transfer/UploadTask'// Bucket name, which consists of bucketname-appid (appid must be included), can be viewed in the COS console. https://console.tencentcloud.com/cos5/bucketlet bucket = "examplebucket-1250000000";//The location identifier of an object in a bucket, also known as the object keylet cosPath = "exampleobject.txt";//Local file pathlet srcPath = "Local file path";//If there is an UploadId for initializing multipart upload, assign the corresponding _uploadId value for resuming; otherwise, assign undefinedlet _uploadId: string | undefined = undefined;// Upload configurationlet transferConfig = new TransferConfig();let putRequest = new PutObjectRequest(bucket, cosPath, srcPath);let task: UploadTask = CosXmlBaseService.default().upload(putRequest, _uploadId, transferConfig);// Upload progress callbacktask.onProgress = (progress: HttpProgress) => {// progress.complete indicates the current uploaded size// progress.target is the total size};// http request time-consuming callbacktask.onTimeInfo = (request: CosXmlRequest, timeInfo: rcp.TimeInfo) => {// request: current request information// timeInfo: time-consuming information}task.onResult = {// Upload success callbackonSuccess: (request, result: CosXmlUploadTaskResult) => {// todo Logic after successful upload},//Upload failure callbackonFail: (request, error: CosError) => {// todo Logic after upload failure}}// Initialization complete callbacktask.initCallBack = (uploadId) =>{// uploadId for the next resumable upload_uploadId = uploadId;}// Start uploadtask.start();// Pause task// task.pause();// Resume task// task.resume();// Cancel task// task.cancel();
Parameter Name | Description | Type | Default Value | Required or Not |
simpleUploadLimit | Simple upload limit: If the file size is less than this value, use simple upload; otherwise, use multipart upload. | number | 1 * 1024 * 1024 | No |
sliceLength | The size of each part in multipart upload. | number | 1 * 1024 * 1024 | No |
{"version": "2.0","statement": [{"action": [//head operation"name/cos:HeadObject",//Downloading operation"name/cos:GetObject",],"effect": "allow","resource": ["qcs::cos:ap-beijing:uid/1250000000:examplebucket-1250000000/doc/*"]}]}
import { CosXmlBaseService, HttpProgress, GetObjectRequest, DownloadTask, CosError } from '@tencentcloud/cos';import { CosXmlDownloadTaskResult } from '@tencentcloud/cos/src/main/ets/transfer/DownloadTask'// Bucket name, which consists of bucketname-appid (appid must be included), can be viewed in the COS console. https://console.tencentcloud.com/cos5/bucketlet bucket = "examplebucket-1250000000";//The location identifier of an object in a bucket, also known as the object keylet cosPath = "exampleobject.txt";// Local file download path. If the file does not exist, the sdk will automatically create it.let downliadPath = "Local file path";let getRequest = new GetObjectRequest(bucket, cosPath, downliadPath);let task: DownloadTask = CosXmlBaseService.default().download(getRequest);// Download progress callbacktask.onProgress = (progress: HttpProgress) => {// progress.complete indicates the currently downloaded size// progress.target is the total size};task.onResult = {// Download success callbackonSuccess: (request, result: CosXmlDownloadTaskResult) => {// todo Logic after successful download},// Download failure callbackonFail: (request, error: CosError) => {// todo Logic after download failure}}// Start downloadtask.start();// Pause task// task.pause();// Resume task// task.resume();// Cancel task// task.cancel();
Feedback