npm install --save react-native-cos-sdk
yarn add react-native-cos-sdk
import Cos from 'react-native-cos-sdk';
// Obtain temporary keys (controlled at the business layer)let tmpSecretId = "SECRETID"; // Temporary key SecretIdlet tmpSecretKey = "SECRETKEY"; // Temporary key SecretKeylet sessionToken = "SESSIONTOKEN"; // Temporary key Tokenlet 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 devicelet startTime = 1556182000; // Temporary key validity start time, in secondsconst sessionCredentials = {tmpSecretId: tmpSecretId,tmpSecretKey: tmpSecretKey,startTime: startTime,expiredTime: expiredTime,sessionToken: sessionToken};// Subsequently, pass sessionQCloudCredentials to specific COS operation methods
import Cos from 'react-native-cos-sdk';Cos.initWithSessionCredentialCallback(async () => {// First, obtain the response containing key information from your temporary key server, for example:// url for the temporary key server. For the temporary key generation service, see https://www.tencentcloud.com/document/product/436/14048let stsUrl = "http://stsservice.com/sts";let response = null;try{response = await fetch(stsUrl);} catch(e){console.error(e);return null;}// Then parse the response to obtain temporary key informationconst responseJson = await response.json();const credentials = responseJson.credentials;const startTime = responseJson.startTime;const expiredTime = responseJson.expiredTime;const sessionCredentials = {tmpSecretId: credentials.tmpSecretId,tmpSecretKey: credentials.tmpSecretKey,startTime: startTime, // startTime is a 10-digit timestamp.expiredTime: expiredTime, // expiredTime is a 10-digit timestamp.sessionToken: credentials.sessionToken};console.log(sessionCredentials);// Finally, return the temporary key information objectreturn sessionCredentials;})
import Cos from 'react-native-cos-sdk';let SECRET_ID = "SECRETID"; // Permanent key secretIdlet SECRET_KEY = "SECRETKEY"; // Permanent key secretKeyCos.initWithPlainSecret(SECRET_ID,SECRET_KEY)
// The abbreviation for the bucket region, such as ap-guangzhou for Guangzhoulet region = "COS_REGION";// Create a CosXmlServiceConfig object and modify the default configuration parameters as neededlet serviceConfig = {region: region,isDebuggable: true,isHttps: true,};// Register the default COS Servicelet cosService = await Cos.registerDefaultService(serviceConfig);// Obtain the default COS Servicelet cosService1 = Cos.getDefaultService();// 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.let 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 TransferMangerlet cosTransferManger = await Cos.registerDefaultTransferManger(serviceConfig, transferConfig);// Obtain the default COS TransferMangerlet cosTransferManger1 = Cos.getDefaultTransferManger();// You can also register other instances using registerService and registerTransferManger for subsequent calls.// Generally, region is used as the registration keylet newRegion = "NEW_COS_REGION";serviceConfig.region = newRegion;let cosServiceNew = await Cos.registerService(newRegion, serviceConfig);let cosTransferMangerNew = await Cos.registerTransferManger(newRegion, serviceConfig, transferConfig);// Obtain COS Service and COS TransferManger via keylet cosServiceNew1 = Cos.getService(newRegion);let cosTransferMangerNew1 = Cos.getTransferManger(newRegion);
const SERVICE_CONFIG = {region: "COS_REGION",isDebuggable: true,}export async function getDefaultService(): Promise<CosService> {if(Cos.hasDefaultService()){return Cos.getDefaultService()} else {// Register the default servicereturn await Cos.registerDefaultService(SERVICE_CONFIG)}}
Parameter Name | Description | Type | Default Value | Supported Platforms |
region | The region of the bucket. For details, see Regions and Access Domains | String | null | Android and iOS |
connectionTimeout | Connection timeout time (in milliseconds) | Int | Android(15000) iOS(30000) | Android and iOS |
socketTimeout | Read/write timeout time (in milliseconds) | Int | 30000 | Android |
isHttps | Whether to use the https protocol | Bool | true | Android and iOS |
host | Set the host for all requests except GetService. | String | null | Android and iOS |
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, if you set hostFormat to ${bucket}.${region}.tencent.com, and your bucket and region are bucket-1250000000 and ap-shanghai respectively, the final request address will be bucket-1250000000.ap-shanghai.tencent.comNote: This setting does not affect GetService requests. | String | null | Android |
port | Set the request port. | Int | null | Android |
isDebuggable | whether it is in debug mode (debug mode prints debug logs) | Bool | false | Android |
signInUrl | Whether to place the signature in the URL, which is placed in the Header by default. | Bool | false | Android |
userAgent | ua extension parameters | String | null | Android and iOS |
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 |
accelerate | Whether to use Global Accelerator domain names. | Bool | false | Android and iOS |
Parameter Name | Description | Type | Default Value | Supported Platforms |
divisionForUpload | Set the minimum object size for chunked upload. | Int | 2097152 | Android and iOS |
sliceSizeForUpload | Set the part size for chunked upload. | Int | 1048576 | Android and iOS |
enableVerification | Whether to verify the integrity during chunked upload | Bool | true | Android and iOS |
forceSimpleUpload | Whether to force the use of simple upload. | Bool | false | Android |
// Obtain CosTransferMangerlet cosTransferManger: CosTransferManger = Cos.getDefaultTransferManger();//let cosTransferManger: CosTransferManger = 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/bucketlet bucket = "examplebucket-1250000000";let cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object keylet srcPath = "local file path"; // local file path// If an UploadId for an initialized multipart upload exists, assign its value to uploadId for resuming; otherwise, assign undefinedlet _uploadId = undefined;// Upload success callbacklet successCallBack = (header?: object) => {// todo Upload success follow-up logic};// Upload failure callbacklet failCallBack = (clientError?: CosXmlClientError, serviceError?: CosXmlServiceError) => {// todo Upload failure follow-up logicif (clientError) {console.log(clientError);}if (serviceError) {console.log(serviceError);}};// Upload status callback, which allows you to view the task progresslet stateCallBack = (state: TransferState) => {// todo notify transfer state};// Upload progress callbacklet progressCallBack = (complete: number, target: number) => {// todo Do something to update progress...};// Initialization chunk complete callbacklet initMultipleUploadCallBack = (bucket: string, cosKey: string, uploadId: string) => {// Used to resume the upload next time, uploadId_uploadId = uploadId;};// Start uploadlet transferTask:TransferTask = await cosTransferManger.upload(bucket,cosPath,srcPath,{uploadId: _uploadId,resultListener: {successCallBack: successCallBack,failCallBack: 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: sessionCredentials});// 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.// CosTransferManager supports resumable downloads; 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 CosTransferMangerlet cosTransferManger: CosTransferManger = Cos.getDefaultTransferManger();//let cosTransferManger: CosTransferManger = 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/bucketlet bucket = "examplebucket-1250000000";let cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object keylet downliadPath = "local file path"; // path to save the local file// Download success callbacklet successCallBack = (header?: object) => {// todo Download success follow-up logic};// Download failure callbacklet failCallBack = (clientError?: CosXmlClientError, serviceError?: CosXmlServiceError) => {// todo Download failure follow-up logicif (clientError) {console.log(clientError);}if (serviceError) {console.log(serviceError);}};// Download status callback, which allows you to view the task progresslet stateCallBack = (state: TransferState) => {// todo notify transfer state};// Download progress callbacklet progressCallBack = (complete: number, target: number) => {// todo Do something to download progress...};// Start downloadlet transferTask:TransferTask = await cosTransferManger.download(bucket,cosPath,downliadPath,{resultListener: {successCallBack: successCallBack,failCallBack: 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: sessionCredentials});// Pause task//transferTask.pause();// Resume task//transferTask.resume();// Cancel task//transferTask.cancel();
Feedback