tencent cloud

Cloud Object Storage

PUT Object

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2026-02-02 17:39:33

Introduction

This document provides an overview of the APIs related to operations such as advanced upload, simple upload, multipart upload, and others, as well as SDK sample code.
Simple operations
API
Operation Name
Operation Description
Uploading Objects in Simple Upload Mode
Upload an object to a bucket.
Part operations
API
Operation Name
Operation Description
Querying Multipart Upload
Query information about ongoing multipart upload tasks.
Initializing Multipart Upload
Initialize a multipart upload task.
Uploading Parts
Upload the object using multipart upload
Querying Uploaded Parts
Query uploaded parts in a specified multipart upload operation.
Completing Multipart Upload
Complete multipart upload of the entire file.
Terminating Multipart Upload
Terminate a multipart upload operation and delete uploaded parts.
Note:
Presigned uploads are only applicable to simple uploads.

Advanced API (recommended)

Uploading an Object

Advanced interface encapsulates the simple upload and multipart upload interfaces, intelligently selects the upload method based on file size, and supports the resumable feature.

Authorization Description

When you perform authorization policy for action, see the following example.
{
"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 ongoing multipart upload operations
"name/cos:ListMultipartUploads",
//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/*"
]
}
]
}
For more COS actions, see CAM-authorized service interfaces.

Sample Code 1: Uploading a Local File

// Instantiate PutObjectRequest, set the bucket name, destination path, and local file path.
// Bucket name: which consists of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket
// Destination path for upload: which is the full path of the object on COS. If including a directory, the format should be "video/xxx/movie.mp4"
// Local file: file path.
let putRequest = new PutObjectRequest("bucket name", "destination path", "local file");

// Use the CosXmlBaseService instance to call the upload method to obtain the current upload task. For the specific usage of CosXmlBaseService, see CosXmlBaseService.
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust);

// Set initCallBack to obtain the multipart upload uploadId (simple upload does not return uploadId)
task.initCallBack = (uploadId:string)=>{
this.uploadId = uploadId;
}
// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
//complete: The number of bytes sent
//target: The total number of bytes to be sent in this upload (which is the size of a single file)
};

// Set the completion callback
task.onResult = {
// Success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// Failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
// Start the task task.start()
Note:
After uploading, you can use the same Key to generate a file download link. For specific usage, see the Generate a Presigned URL document. Note that if your file has private read access, the download link is only valid for a limited period.

Sample Code 2: Upload Binary Data

// Instantiate PutObjectRequest, set the bucket name, destination path, and file content ArrayBuffer.
// When uploading data in ArrayBuffer format, pause and resume is not supported.
// // Bucket name: which consists of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket // Upload target path: the full path of the object on COS. If it includes a directory, the format is "video/xxx/movie.mp4" // buffer: file content, type is ArrayBuffer.
let buffer:ArrayBuffer = ;
let putRequest = new PutObjectRequest("bucket name", "destination path", buffer);

// Use the CosXmlBaseService instance to call the upload method to obtain the current upload task. For the specific usage of CosXmlBaseService, see CosXmlBaseService.
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust);

// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
//complete: The number of bytes sent
//target: The total number of bytes to be sent in this upload (which is the size of a single file)
};

// Set the completion callback
task.onResult = {
// Success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// Failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
// Start the task task.start()
Note:
After uploading, you can use the same Key to generate a file download link. For specific usage, see the Generate a Presigned URL document. Note that if your file has private read access, the download link is only valid for a limited period.

Sample Code 3: Upload Pause, Resume, and Cancel

For an upload task, it can be paused in the following ways:
// Pause: Pauses the current task without clearing uploaded files. task.pause();
After pausing, it can be resumed in the following ways:
Call task.resume(). This is applicable when the task has not been destroyed.
// Resume: Restarts the paused task. task.resume();
Resume the upload using the locally saved uploadId. This is applicable when the app process is terminated and needs to resume uploading after restarting (the uploadId must be persistently stored locally by the business side).
// Instantiate PutObjectRequest, set the bucket name, destination path, and local file.
let putRequest = new PutObjectRequest("bucket name", "destination path", "local file");
// Use the CosXmlBaseService instance to call the upload method to obtain the current upload task. For the specific usage of CosXmlBaseService, see CosXmlBaseService.
// uploadId: The uploadId for resuming the upload task, which must be persisted by the business side. It is obtained from the task.initCallBack callback.
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust,uploadId);
// Set initCallBack to obtain the multipart upload uploadId (simple upload does not return uploadId)
task.initCallBack = (uploadId:string)=>{
this.uploadId = uploadId;
}
// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
//complete: The number of bytes sent
//target: The total number of bytes to be sent in this upload (which is the size of a single file)
};
// Set the completion callback
task.onResult = {
// Success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// Failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
task.start()
Cancel the upload by the following ways:
Cancel: Cancels the current upload task and deletes uploaded temporary files. After cancellation, resuming is no longer supported. task.cancel();

Sample Code 4: Set Temporary Key Separately

// Initialize putRequest;
let putRequest = new PutObjectRequest("bucket name", "destination path", "local file");
let credential = new QCloudCredential(); credential.secretID = ''; credential.secretKey = ''; credential.token = '';
// Set the temporary key information for the current request.
putRequest.credential = credential;
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust);
task.initCallBack = (uploadId:string)=>{
this.uploadId = uploadId;
}
// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
// complete: Bytes sent
// target: The total number of bytes to be sent in this upload (which is the size of a single file)
};
// Set the completion callback
task.onResult = {
// Success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// Failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
task.start()

Sample Code 5: Batch Upload

for (int i = 0; i<20; i++) {
let putRequest = new PutObjectRequest("bucket name", "upload target path", "local file");
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust);
task.initCallBack = (uploadId:string)=>{
this.uploadId = uploadId;
}
// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
// complete: bytes sent
// target: total bytes to be sent for this upload (i.e., the file size)
};
// Set the completion callback
task.onResult = {
// success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
task.start()
}

Sample Code 6: Custom Threshold for Simple Upload and Multipart Upload

let putRequest = new PutObjectRequest("bucket name", "destination path", "local file");

// Initialize TransferConfig;
let config = new TransferConfig();
// Set the part size threshold to: 2M. config.simpleUploadLimit = 2 * 1024 * 1024;
// Call the upload method and pass in config;
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust,undefined,config);
task.initCallBack = (uploadId:string)=>{
this.uploadId = uploadId;
}
// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
// complete: bytes sent
// target: total bytes to be sent for this upload (i.e., the file size)
};
// Set the completion callback
task.onResult = {
// success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
task.start()

Example Code 7: Custom Part Size

let putRequest = new PutObjectRequest("bucket name", "destination path", "local file");

// Initialize TransferConfig;
let config = new TransferConfig();
// Set the chunk size to: 1M. config.sliceLength = 1 * 1024 * 1024;
// Call the upload method and pass in config;
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust,undefined,config);
task.initCallBack = (uploadId:string)=>{
this.uploadId = uploadId;
}
// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
// complete: bytes sent
// target: total bytes to be sent for this upload (i.e., the file size)
};
// Set the completion callback
task.onResult = {
// success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
task.start()

Sample Code Eight: Rate Limiting During Upload

// Initialize putRequest;
let putRequest = new PutObjectRequest("bucket name", "destination path", "local file");
// The rate limit setting range is 819200 - 838860800, that is, 800Kb/s - 800Mb/s.
putRequest.addHeader('x-cos-traffic-limit','819200')
let task:UploadTask = CosXmlBaseService.default().upload(putReqeust);
task.initCallBack = (uploadId:string)=>{
this.uploadId = uploadId;
}
// Set the upload progress callback
task.onProgress = (progress: HttpProgress) => {
//complete: The number of bytes sent
// target: The total number of bytes to be sent in this upload (which is the size of a single file)
};
// Set the completion callback
task.onResult = {
// Success callback
onSuccess: (request, result) => {
// request: current request
// resultL: response result
},
// Failure callback
onFail: (request, error) => {
// request: current request
// error: error message
}
}
task.start()

Simple Operations

Uploading Objects in Simple Upload Mode

Feature Overview

The PUT Object interface can upload an object to a specified bucket. This operation requires the requester to have WRITE permission on the bucket. It supports uploading objects up to 5GB in size. For objects larger than 5GB, use multipart upload or advanced APIs for uploading.
Note:
Keys (upload target paths) cannot end with /, otherwise they will be identified as folders.

Example Code

// Initialize putRequest;
let putRequest = new PutObjectRequest("bucket name", "destination path", "local file");
// Set progress callback
request.onProgress = (progress: HttpProgress) => {
//complete: The number of bytes sent
//target: The total number of bytes to be sent in this upload (which is the size of a single file)
};
try { let result:PutObjectResult = await CosXmlBaseService.default().putObject(request);
} catch (e) { }
Note:
After uploading, you can use the same Key to generate a file download link. For specific usage, see the Generate a Presigned URL document. Note that if your file has private read access, the download link is only valid for a limited period.

Multipart Operations

For more information on multipart upload, see Multipart Upload. The procedure for multipart upload operations is as follows.

Introduction to the Multipart Upload Process

Process of Multipart Upload

1. Initiate Multipart Upload (Initiate Multipart Upload) to obtain the UploadId.
2. Uploading parts using UploadId (Upload Part).
3. Complete multipart upload (Complete Multipart Upload).

Process for Resuming Multipart Upload

1. List uploaded parts using UploadId (List Parts).
2. Upload the remaining parts using UploadId (Upload Part).
3. Complete multipart upload (Complete Multipart Upload).
Note:
The size of each Part, except the last one, must not be smaller than 1MB; otherwise, it will result in a failure when the Complete Multipart Upload interface is called.
After the file to be uploaded is split into Parts, the file sequence is determined by the partNumber specified during the upload process. In practice, no sequential order is required, enabling concurrent uploads.
Increasing the number of concurrent uploads does not necessarily result in faster speeds. It should be comprehensively considered based on the user's network conditions and device load. When network conditions are favorable, it is recommended to increase the part size. Conversely, reduce the part size accordingly.
By default, Parts that have been uploaded but not yet called with CompleteMultipartUpload will not be automatically cleaned up. They occupy storage space and incur storage costs. Therefore, to terminate the upload and free up the occupied space, call AbortMultipartUpload.

Initializing Multipart Upload

Feature Overview

Initialize the Multipart Upload upload operation and obtain the corresponding uploadId (Initiate Multipart Upload).

Example Code

let request = new InitMultipartUploadRequest("bucket name", "target upload path"); try { let result:InitMultipartUploadResult = await CosXmlBaseService.default().initMultipartUpload(request); } catch (e) { }

Uploading Parts

Feature Overview

Objects uploaded in mulitparts.

Example Code

// Instantiate the part information, including the length of each part, the current part offset, and the local file path.
let body = new FilePartInfo('length','offset','local path');
// partNumber: the current part index, starting from 1.
let request = new UploadPartRequest("bucket name","target upload path",(body.index).toString(),body); try { request.onProgress = (progress) => { // progress callback }; request.onSuccess = (response) => { // Part upload succeeded let headers = response!.headers; if (headers) {
// Upon successful upload, store the etag and index.
// After all parts are uploaded, call the complete upload interface with this information. let etag = headers[HttpHeader.ETAG]; let info = new CompleteMultipartUploadPart(parseInt((body.index + 1).toString()),etag); this.uploadedParts.add(info); } }; request.onFailure = (err: Error) => { // Part upload failed };
CosXmlBaseService.default().partUpload(request); } catch (e) { }

List Parts

Feature Overview

Query the uploaded mulitparts in a specific multiple parts uploading (List Parts).

Example Code

// Method to query the uploaded parts in a specific multipart upload.
// Specify the uploadId for this multipart upload.
let request = new ListPartsRequest("bucket name", "target upload path", uploadId);
try{
result = await CosXmlBaseService.default().listParts(request);
}catch(e){
}

Completing Multipart Upload

Feature Overview

Complete multipart upload of the entire file.

Example Code

let request = new CompleteMultiUploadRequest("bucket name", "target upload path", uploadId);
// Sort all parts. this.uploadedParts.sort((obj1:CompleteMultipartUploadPart,obj2:CompleteMultipartUploadPart)=>{ if (obj1.partNumber < obj2.partNumber) { return -1; }else{ return 1; } })
// Initialize CompleteMultipartUpload let completeInput = new CompleteMultipartUpload(); completeInput.part = this.uploadedParts; request.completeMultipartUpload = completeInput; try { let result = await CosXmlBaseService.default().completeMultiUpload(request); } catch (e) { }

Terminating Multipart Upload

Feature Overview

Abort a mulitpart uploading operation and delete the uploaded parts.

Example Code

// Method to abort a multipart upload and delete the uploaded parts.
let request = new AbortMultiUploadRequest("bucket name", "target upload path", uploadId); try { await CosXmlBaseService.default().abortMultiUpload(request); } catch (e) { this.onFail(this.request,e); }


Ajuda e Suporte

Esta página foi útil?

comentários