tencent cloud

Cloud Object Storage

동향 및 공지
릴리스 노트
제품 공지
제품 소개
제품 개요
기능 개요
적용 시나리오
제품 장점
기본 개념
리전 및 액세스 도메인
규격 및 제한
제품 요금
과금 개요
과금 방식
과금 항목
프리 티어
과금 예시
청구서 보기 및 다운로드
연체 안내
FAQ
빠른 시작
콘솔 시작하기
COSBrowser 시작하기
사용자 가이드
요청 생성
버킷
객체
데이터 관리
일괄 프로세스
글로벌 가속
모니터링 및 알람
운영 센터
데이터 처리
스마트 툴 박스 사용 가이드
데이터 워크플로
애플리케이션 통합
툴 가이드
툴 개요
환경 설치 및 설정
COSBrowser 툴
COSCLI 툴
COSCMD 툴
COS Migration 툴
FTP Server 툴
Hadoop 툴
COSDistCp 툴
HDFS TO COS 툴
온라인 도구 (Onrain Dogu)
자가 진단 도구
실습 튜토리얼
개요
액세스 제어 및 권한 관리
성능 최적화
AWS S3 SDK를 사용하여 COS에 액세스하기
데이터 재해 복구 백업
도메인 관리 사례
이미지 처리 사례
COS 오디오/비디오 플레이어 사례
데이터 다이렉트 업로드
데이터 보안
데이터 검증
빅 데이터 사례
COS 비용 최적화 솔루션
3rd party 애플리케이션에서 COS 사용
마이그레이션 가이드
로컬 데이터 COS로 마이그레이션
타사 클라우드 스토리지 데이터를 COS로 마이그레이션
URL이 소스 주소인 데이터를 COS로 마이그레이션
COS 간 데이터 마이그레이션
Hadoop 파일 시스템과 COS 간 데이터 마이그레이션
데이터 레이크 스토리지
클라우드 네이티브 데이터 레이크
메타데이터 가속
데이터 레이크 가속기 GooseFS
데이터 처리
데이터 처리 개요
이미지 처리
미디어 처리
콘텐츠 조정
파일 처리
문서 미리보기
장애 처리
RequestId 가져오기
공용 네트워크로 COS에 파일 업로드 시 속도가 느린 문제
COS 액세스 시 403 에러 코드 반환
리소스 액세스 오류
POST Object 자주 발생하는 오류
보안 및 컴플라이언스
데이터 재해 복구
데이터 보안
액세스 관리
자주 묻는 질문
인기 질문
일반 문제
과금
도메인 규정 준수 문제
버킷 설정 문제
도메인 및 CDN 문제
파일 작업 문제
로그 모니터링 문제
권한 관리
데이터 처리 문제
데이터 보안 문제
사전 서명 URL 관련 문제
SDK FAQ
툴 관련 문제
API 관련 문제
Agreements
Service Level Agreement
개인 정보 보호 정책
데이터 처리 및 보안 계약
연락처
용어집
문서Cloud Object Storage

Getting Started

포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-03-03 15:47:44

Relevant Resources

For SDK source code download, see React Native source code download.
For the sample Demo, see React Native SDK Demo.
For the SDK change log, see CHANGELOG.
For the npm address, see npm address.

Environment Configuration and Preparation

You need a pure React Native project or a React Native-native hybrid project. This application can be your existing project or a new empty project you created. For details, see React Native app development guide.
React Native version requirements: 0.69.7 or higher.

Installing the SDK

react-Native-cos-sdk currently supports iOS and Android, and is implemented by bridging the Native Android and iOS COS SDKs.
1. Run the following command:
Using npm:
npm install --save react-native-cos-sdk
Or use yarn:
yarn add react-native-cos-sdk
2. In your code, you can use import to import and then start using:
import Cos from 'react-native-cos-sdk';
Note:
To continuously track and optimize the quality of the SDK and provide you with a better user experience, we have introduced the Tencent Beacon SDK. Tencent Beacon only monitors the request performance on the COS side and will not report business-side data.
If you want to disable this feature, you can replace react-native-cos-sdk with react-native-cos-sdk-nobeacon during dependency import and import.

Initialize COS Service

Note:
It is recommended that users use temporary keys to call the SDK, which further enhances security through temporary authorization. When applying for temporary keys, please follow the principle of least privilege to prevent leakage of resources beyond the target bucket or objects.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the scope of permissions for the permanent keys.
For your business security, please refer to Upload Security Restrictions for file uploads.

Set API Access Key

Single-Use Temporary Key
Temporary Key Callback
Fixed Key (for testing only)
Set the individual key to the sessionCredentials parameter of specific COS operation methods (such as the upload method), and this key is only used for the current COS operation (such as upload and so on).
// Obtain temporary keys (controlled at the business layer)
let tmpSecretId = "SECRETID"; // Temporary key SecretId
let tmpSecretKey = "SECRETKEY"; // Temporary key SecretKey
let sessionToken = "SESSIONTOKEN"; // Temporary key Token
let 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 device
let startTime = 1556182000; // Temporary key validity start time, in seconds
const sessionCredentials = {
tmpSecretId: tmpSecretId,
tmpSecretKey: tmpSecretKey,
startTime: startTime,
expiredTime: expiredTime,
sessionToken: sessionToken
};
// Subsequently, pass sessionQCloudCredentials to specific COS operation methods
Note:
COS SDK version needs to be greater than or equal to v1.1.9.
Provide a callback method to the COS SDK for obtaining temporary keys. The SDK will use this callback to retrieve temporary keys when first initialized and when the cached temporary keys are about to expire.
Call the initWithSessionCredentialCallback method of Cos to implement the process of requesting temporary keys and returning the result.
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/14048
let 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 information
const 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 object
return sessionCredentials;
})
You can use Tencent Cloud's permanent keys for local debugging during development. Due to risks of key leakage, you must replace them with temporary keys before deployment.
import Cos from 'react-native-cos-sdk';

let SECRET_ID = "SECRETID"; // Permanent key secretId
let SECRET_KEY = "SECRETKEY"; // Permanent key secretKey

Cos.initWithPlainSecret(
SECRET_ID,
SECRET_KEY
)

Register for the COS Service

// The abbreviation for the bucket region, such as ap-guangzhou for Guangzhou
let region = "COS_REGION";
// Create a CosXmlServiceConfig object and modify the default configuration parameters as needed
let serviceConfig = {
region: region,
isDebuggable: true,
isHttps: true,
};
// Register the default COS Service
let cosService = await Cos.registerDefaultService(serviceConfig);
// Obtain the default COS Service
let 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 chunks
sliceSizeForUpload: 1048576, // Set the default chunk size to 1MB
};
// Register the default COS TransferManger
let cosTransferManger = await Cos.registerDefaultTransferManger(serviceConfig, transferConfig);
// Obtain the default COS TransferManger
let cosTransferManger1 = Cos.getDefaultTransferManger();

// You can also register other instances using registerService and registerTransferManger for subsequent calls.
// Generally, region is used as the registration key
let 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 key
let cosServiceNew1 = Cos.getService(newRegion);
let cosTransferMangerNew1 = Cos.getTransferManger(newRegion);
Note:
Before COS Service and COS TransferManger are obtained, registration must be performed; otherwise, an error will be reported.
For example, you can control the process where registration is mandatory before they are obtained by encapsulating a method similar to the following:
const SERVICE_CONFIG = {
region: "COS_REGION",
isDebuggable: true,
}

export async function getDefaultService(): Promise<CosService> {
if(Cos.hasDefaultService()){
return Cos.getDefaultService()
} else {
// Register the default service
return await Cos.registerDefaultService(SERVICE_CONFIG)
}
}

Parameter Description

CosXmlServiceConfig configures the COS service, and its main members are described as follows:
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.com
Note:
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
TransferConfig configures the COS upload service, and its main members are described as follows:
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

Access COS Service

PUT Object
Downloading an Object
Note:
For more complete examples, visit GitHub.
// Obtain CosTransferManger
let 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/bucket
let bucket = "examplebucket-1250000000";
let cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object key
let 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 undefined
let _uploadId = undefined;

// Upload success callback
let successCallBack = (header?: object) => {
// todo Upload success follow-up logic
};
// Upload failure callback
let failCallBack = (clientError?: CosXmlClientError, serviceError?: CosXmlServiceError) => {
// todo Upload failure follow-up logic
if (clientError) {
console.log(clientError);
}
if (serviceError) {
console.log(serviceError);
}
};
// Upload status callback, which allows you to view the task progress
let stateCallBack = (state: TransferState) => {
// todo notify transfer state
};
// Upload progress callback
let progressCallBack = (complete: number, target: number) => {
// todo Do something to update progress...
};
// Initialization chunk complete callback
let initMultipleUploadCallBack = (bucket: string, cosKey: string, uploadId: string) => {
// Used to resume the upload next time, uploadId
_uploadId = uploadId;
};

// Start upload
let 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 parameter
sessionCredentials: sessionCredentials
}
);
// Pause task
//transferTask.pause();
// Resume task
//transferTask.resume();
// Cancel task
//transferTask.cancel();
Note:
For more complete examples, visit GitHub.
// 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 CosTransferManger
let 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/bucket
let bucket = "examplebucket-1250000000";
let cosPath = "exampleobject"; // The location identifier of the object in the bucket, also known as the object key
let downliadPath = "local file path"; // path to save the local file

// Download success callback
let successCallBack = (header?: object) => {
// todo Download success follow-up logic
};
// Download failure callback
let failCallBack = (clientError?: CosXmlClientError, serviceError?: CosXmlServiceError) => {
// todo Download failure follow-up logic
if (clientError) {
console.log(clientError);
}
if (serviceError) {
console.log(serviceError);
}
};
// Download status callback, which allows you to view the task progress
let stateCallBack = (state: TransferState) => {
// todo notify transfer state
};
// Download progress callback
let progressCallBack = (complete: number, target: number) => {
// todo Do something to download progress...
};

// Start download
let 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 parameter
sessionCredentials: sessionCredentials
}
);
// Pause task
//transferTask.pause();
// Resume task
//transferTask.resume();
// Cancel task
//transferTask.cancel();

FAQs

You may encounter some common issues during use. For related solutions, see React Native SDK FAQ.

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백