Uploading Objects

Last updated: 2023-09-13 15:01:13

Feature Overview

This document provides an overview of APIs and SDK code samples for advanced upload, upload in whole, multipart upload, and other object operations.
Simple operations
API
Operation
Description
Uploading an object using simple upload
Uploads an object to a bucket
Multipart operations
API
Operation
Description
Querying multipart upload
Queries the information on ongoing multipart uploads
Initializing a multipart upload operation
Initializes a multipart upload task
Uploading parts
Uploads a part in multipart upload
Querying uploaded parts
Queries uploaded parts in a specified multipart upload operation
Completing multipart upload
Completes the multipart upload of the entire file
Aborting a multipart upload
Aborts a multipart upload operation and deletes the uploaded parts

SDK API References

For parameters and method description of all APIs in the SDK, see SDK API Reference.

Advanced APIs (Recommended)

Uploading object

The advanced APIs encapsulate the simple upload and multipart upload APIs and can intelligently select the upload method based on file size. They support checkpoint restart for resuming interrupted operations.

Sample 1. Uploading a local file

Objective-C
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
/** Path of the local file. Ensure that the URL starts with "file://" in the following format:
1. [NSURL URLWithString:@"file:////var/mobile/Containers/Data/Application/DBPF7490-D5U8-4ABF-A0AF-CC49D6A60AEB/Documents/exampleobject"]
2. [NSURL fileURLWithPath:@"/var/mobile/Containers/Data/Application/DBPF7490-D5U8-4ABF-A0AF-CC49D6A60AEB/Documents/exampleobject"]
*/
NSURL* url = [NSURL fileURLWithPath:@"file URL"];
// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";
// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = @"exampleobject";
// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
put.body = url;
// Monitor the upload progress
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
}];
// Monitor the upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from the result.location in the upload result
NSString * fileUrl = result.location;
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];
[put setInitMultipleUploadFinishBlock:^(QCloudInitiateMultipartUploadResult *
multipleUploadInitResult,
QCloudCOSXMLUploadObjectResumeData resumeData) {
// After initializing the multipart upload, this callback block will be executed, where you can obtain the resumeData and uploadId.
NSString* uploadId = multipleUploadInitResult.uploadId;
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];

Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.
Swift
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = "exampleobject";

// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
put.body = NSURL.fileURL(withPath: "Local File Path") as AnyObject;

// Monitor the upload result
put.setFinish { (result, error) in
// Retrieve the upload result
if let result = result {
// File's etag
let eTag = result.eTag
// File download link
let location = result.location;
// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}

// Monitor the upload progress
put.sendProcessBlock = { (bytesSent, totalBytesSent,
totalBytesExpectedToSend) in
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
};
// Set the upload parameters
put.initMultipleUploadFinishBlock = {(multipleUploadInitResult, resumeData) in
// After initializing the multipart upload, this block will be called, where you can obtain the resumeData and uploadId.
if let multipleUploadInitResult = multipleUploadInitResult {
let uploadId = multipleUploadInitResult.uploadId
}
}

QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.

Sample code 2. Uploading binary data

Objective-C
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = @"exampleobject";

// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
put.body = [@"My Example Content" dataUsingEncoding:NSUTF8StringEncoding];

// Monitor the upload progress
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// bytesSent Added bytes
// totalBytesSent Total bytes uploaded in this session
// totalBytesExpectedToSend Target number of bytes to be uploaded locally
}];

// Monitor the upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from the result.location in the upload result
NSString * fileUrl = result.location;
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.
Swift
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = "exampleobject";

// Content of the object to be uploaded
let dataBody:NSData = "wrwrwrwrwrw".data(using: .utf8)! as NSData;
put.body = dataBody;

// Monitor the upload result
put.setFinish { (result, error) in
// Retrieve the upload result
if let result = result {
// File's etag
let eTag = result.eTag

// File download link
let location = result.location;

// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}

// Monitor the upload progress
put.sendProcessBlock = { (bytesSent, totalBytesSent,
totalBytesExpectedToSend) in

// bytesSent Added bytes
// totalBytesSent Total bytes uploaded in this session
// totalBytesExpectedToSend Target number of bytes to be uploaded locally
};

QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.

Sample code 3. Suspending, resuming, and canceling an upload

Objective-C
To suspend an upload, use the code below:
NSError *error;
NSData *resmeData = [put cancelByProductingResumeData:&error];
To resume a suspended download, use the code below:
QCloudCOSXMLUploadObjectRequest *resumeRequest = [QCloudCOSXMLUploadObjectRequest requestWithRequestData:resmeData];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:resumeRequest];
To cancel an upload, run this code:
// Abort the upload.
[put abort:^(id outputObject, NSError *error) {

}];
Note
For the complete sample, go to GitHub.
Swift
To suspend an upload, use the code below:
var error : NSError?;
var uploadResumeData:Data = put.cancel(byProductingResumeData:&error) as Data;
To resume a suspended download, use the code below:
var resumeRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>.init(request: uploadResumeData);
QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(resumeRequest);
To cancel an upload, run this code:
// Abort the upload.
put.abort { (outputObject, error) in

}
Note
For the complete sample, go to GitHub.

Sample code 4. Uploading multiple objects

Objective-C
for (int i = 0; i<20; i++) {
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = [NSString stringWithFormat:@"exampleobject-%d",i];

// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
put.body = [@"My Example Content" dataUsingEncoding:NSUTF8StringEncoding];

// Monitor the upload progress
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
}];

// Monitor the upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from the result.location in the upload result
NSString * fileUrl = result.location;

// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}
Swift
for i in 1...10 {
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = "exampleobject-".appendingFormat("%d", i);

// Content of the object to be uploaded
let dataBody:NSData = "wrwrwrwrwrw".data(using: .utf8)! as NSData;
put.body = dataBody;

// Monitor the upload result
put.setFinish { (result, error) in
// Retrieve the upload result
if let result = result {
// File's etag
let eTag = result.eTag

// File download link
let location = result.location;

// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}

// Monitor the upload progress
put.sendProcessBlock = { (bytesSent, totalBytesSent,
totalBytesExpectedToSend) in

// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
};

QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
}

Sample code 5. Customizing the threshold to trigger multipart upload

Objective-C
for (int i = 0; i<20; i++) {
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = [NSString stringWithFormat:@"exampleobject-%d",i];

// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
put.body = [@"My Example Content" dataUsingEncoding:NSUTF8StringEncoding];
// Customize the threshold for simple upload and multipart upload: By default, multipart upload is enabled when the file size exceeds 1 MB.
put.mutilThreshold = 10 *1024*1024;
// Monitor the upload progress
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
}];

// Monitor the upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from the result.location in the upload result
NSString * location = result.location;
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}
Swift
for i in 1...10 {
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = "exampleobject-".appendingFormat("%d", i);

// Content of the object to be uploaded
let dataBody:NSData = "wrwrwrwrwrw".data(using: .utf8)! as NSData;
put.body = dataBody;
// Customize the threshold for simple upload and multipart upload: By default, multipart upload is enabled when the file size exceeds 1 MB.
put.mutilThreshold = 10 *1024*1024;
// Monitor the upload result
put.setFinish { (result, error) in
// Retrieve the upload result
if let result = result {
// File's etag
let eTag = result.eTag
// File download link
let location = result.location;
// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}

// Monitor the upload progress
put.sendProcessBlock = { (bytesSent, totalBytesSent,
totalBytesExpectedToSend) in

// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
};

QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
}

Sample code 6. Customizing the part size

Objective-C
for (int i = 0; i<20; i++) {
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = [NSString stringWithFormat:@"exampleobject-%d",i];

// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
put.body = [@"My Example Content" dataUsingEncoding:NSUTF8StringEncoding];
// Custom shard size, default is 1MB
put.sliceSize = 10 *1024*1024;
// Monitor the upload progress
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
}];

// Monitor the upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from the result.location in the upload result
NSString * location = result.location;
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}
Swift
for i in 1...10 {
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = "exampleobject-".appendingFormat("%d", i);

// Content of the object to be uploaded
let dataBody:NSData = "wrwrwrwrwrw".data(using: .utf8)! as NSData;
put.body = dataBody;
// Custom shard size, default is 1MB
put.sliceSize = 10 *1024*1024
// Monitor the upload result
put.setFinish { (result, error) in
// Retrieve the upload result
if let result = result {
// File's etag
let eTag = result.eTag

// File download link
let location = result.location;

// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}

// Monitor the upload progress
put.sendProcessBlock = { (bytesSent, totalBytesSent,
totalBytesExpectedToSend) in
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
};

QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
}

Sample code 7. Limiting the upload speed

Note
Requires COS iOS SDK v5.8.0 or higher.
Objective-C
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = [NSString stringWithFormat:@"exampleobject-%d",i];

// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
put.body = [@"My Example Content" dataUsingEncoding:NSUTF8StringEncoding];

// Use the trafficLimit parameter to set the upload speed limit, in bits/s. The speed limit range is 819200 - 838860800, i.e., 800 Kb/s - 800 Mb/s.
put.trafficLimit = 819200;
// Monitor the upload progress
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
}];

// Monitor the upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from the result.location in the upload result
NSString * location = result.location;
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];

Swift

let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = "exampleobject-".appendingFormat("%d", i);

// Content of the object to be uploaded
let dataBody:NSData = "wrwrwrwrwrw".data(using: .utf8)! as NSData;
put.body = dataBody;
// Use the trafficLimit parameter to set the upload speed limit, in bits/s. The speed limit range is 819200 - 838860800, i.e., 800 Kb/s - 800 Mb/s.
put.trafficLimit = 819200;
// Monitor the upload result
put.setFinish { (result, error) in
// Retrieve the upload result
if let result = result {
// File's etag
let eTag = result.eTag

// File download link
let location = result.location;
// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}

// Monitor the upload progress
put.sendProcessBlock = { (bytesSent, totalBytesSent,
totalBytesExpectedToSend) in
// bytesSent Number of bytes to be sent in this instance (a large file may require multiple transmissions)
// totalBytesSent Total bytes sent
// totalBytesExpectedToSend Total number of bytes to be sent in this upload (i.e., the file size)
};

QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);


Sample code 8. Creating a directory

Objective-C
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";
// Name of the directory to create
put.object = @"dir1";

// Content of the object to be uploaded. If you need to create a directory, you only need to use a null string to generate NSData
put.body = [@"" dataUsingEncoding:NSUTF8StringEncoding];

// Monitor the upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from the result.location in the upload result
NSString * location = result.location;
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.
Swift
let put:QCloudCOSXMLUploadObjectRequest = QCloudCOSXMLUploadObjectRequest<AnyObject>();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = "dir/";

// Content of the object to be uploaded
let dataBody:NSData = "".data(using: .utf8)! as NSData;
put.body = dataBody;

// Monitor the upload result
put.setFinish { (result, error) in
// Retrieve the upload result
if let result = result {
// File download link
let location = result.location;

} else {
print(error!);
}
}
QCloudCOSTransferMangerService.defaultCOSTransferManager().uploadObject(put);
Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.

Simple Operations

Uploading an object using simple upload

Note

This API is used to upload an object to a specified bucket. This operation requires the requester to have WRITE permission for the bucket and can upload a file of up to 5 GB in size. For larger files, please use multipart upload or advanced APIs.
Note
A key (filename) must not end with a /, otherwise it will be recognized as a folder.

Sample code

Objective-C
QCloudPutObjectRequest* put = [QCloudPutObjectRequest new];

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
put.object = @"exampleobject";

// Content of the object. You can pass in variables in NSData* or NSURL* format.
put.body = [@"testFileContent" dataUsingEncoding:NSUTF8StringEncoding];

[put setFinishBlock:^(id result, NSError *error) {
// The result contains the response header information
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];

[[QCloudCOSXMLService defaultCOSXML] PutObject:put];
Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.
Swift
let putObject = QCloudPutObjectRequest<AnyObject>.init();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
putObject.bucket = "examplebucket-1250000000";
// Content of the object to be uploaded. You can pass in variables in NSData* or NSURL* format
let dataBody:NSData? = "wrwrwrwrwrw".data(using: .utf8) as NSData?;
putObject.body = dataBody!;

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
putObject.object = "exampleobject";
putObject.finishBlock = {(result,error) in
if let result = result {
// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}
QCloudCOSXMLService.defaultCOSXML().putObject(putObject);
Note
For the complete sample, go to GitHub.
After an object is uploaded, you can use the same key to generate a file download link as instructed in Generating a Pre-signed Link. However, please note that if your file is set to private-read, the download link will only be valid for a certain period of time.

Multipart Operations

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

Performing a multipart upload

1. Initialize the multipart upload with Initiate Multipart Upload and get the UploadId.
2. Use the UploadId to upload the parts with Upload Part.
3. Complete the multipart upload with Complete Multipart Upload.

Resuming a multipart upload

1. If you did not record the UploadId of the multipart upload, you can query the multipart upload job with List Multipart Uploads to get the UploadId of the corresponding file.
2. Use the UploadId to list the uploaded parts with List Parts.
3. Use the UploadId to upload the remaining parts with Upload Part.
4. Complete the multipart upload with Complete Multipart Upload.

Aborting a multipart upload

1. If you did not record the UploadId of the multipart upload, you can query the multipart upload job with List Multipart Uploads to get the UploadId of the corresponding file.
2. Abort the multipart upload and delete the uploaded parts with Abort Multipart Upload.

Querying multipart upload

Note

This API is used to query in-progress multipart uploads in a specified bucket.

Sample code

Objective-C
QCloudListBucketMultipartUploadsRequest* uploads = [QCloudListBucketMultipartUploadsRequest new];
// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
uploads.bucket = @"examplebucket-1250000000";
// Set the maximum number of multiparts to be returned. Valid value: 1–1000
uploads.maxUploads = 100;
[uploads setFinishBlock:^(QCloudListMultipartUploadsResult* result,
NSError *error) {
// The block information can be returned from the result
// Ongoing multipart upload object
NSArray<QCloudListMultipartUploadContent*> *uploads = result.uploads;
}];
[[QCloudCOSXMLService defaultCOSXML] ListBucketMultipartUploads:uploads];
Note
For the complete sample, go to GitHub.
Swift
let listParts = QCloudListBucketMultipartUploadsRequest.init();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
listParts.bucket = "examplebucket-1250000000";

// Set the maximum number of multiparts to be returned. Valid value: 1–1000
listParts.maxUploads = 100;

listParts.setFinish { (result, error) in
if let result = result {
// All incomplete multipart upload tasks
let uploads = result.uploads;
} else {
print(error!);
}
}
QCloudCOSXMLService.defaultCOSXML().listBucketMultipartUploads(listParts);
Note
For the complete sample, go to GitHub.

Initializing a multipart upload operation

Note

This API is used to initialize a multipart upload operation and get its uploadID.

Sample code

Objective-C
QCloudInitiateMultipartUploadRequest* initRequest = [QCloudInitiateMultipartUploadRequest new];
// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
initRequest.bucket = @"examplebucket-1250000000";
// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
initRequest.object = @"exampleobject";
// This will be returned as object metadata
initRequest.cacheControl = @"cacheControl";
initRequest.contentDisposition = @"contentDisposition";
// Define the ACL attribute of the object. Valid values: private (default), public-read-write, public-read
initRequest.accessControlList = @"public";
// Grant read permission
initRequest.grantRead = @"grantRead";
// Grant full permissions to the grantee.
initRequest.grantFullControl = @"grantFullControl";
[initRequest setFinishBlock:^(QCloudInitiateMultipartUploadResult* outputObject,
NSError *error) {
// Obtain the multipart upload ID, which is required for subsequent uploads. Please save it for future use.
self->uploadId = outputObject.uploadId;

}];

[[QCloudCOSXMLService defaultCOSXML] InitiateMultipartUpload:initRequest];
Note
For the complete sample, go to GitHub.
Swift
let initRequest = QCloudInitiateMultipartUploadRequest.init();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
initRequest.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
initRequest.object = "exampleobject";

initRequest.setFinish { (result, error) in
if let result = result {
// Obtain the multipart upload ID, which is required for subsequent uploads. Please save it for future use.
self.uploadId = result.uploadId;
} else {
print(error!);
}
}
QCloudCOSXMLService.defaultCOSXML().initiateMultipartUpload(initRequest);
Note
For the complete sample, go to GitHub.

Uploading parts

This API (Upload Part) is used to upload parts in a multipart upload.

Sample code

Objective-C
QCloudUploadPartRequest* request = [QCloudUploadPartRequest new];
// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
request.bucket = @"examplebucket-1250000000";
// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
request.object = @"exampleobject";
// Part number
request.partNumber = 1;
// The ID of the multipart upload. When you use the Initiate Multipart Upload API to initialize a multipart upload, you will get an uploadId
request.uploadId = uploadId;
// Supported data types for uploading: NSData*, NSURL (local URL), and QCloudFileOffsetBody*
request.body = [@"testFileContent" dataUsingEncoding:NSUTF8StringEncoding];
[request setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// Upload progress information
// bytesSent Added bytes
// totalBytesSent Total bytes uploaded in this session
// totalBytesExpectedToSend Target number of bytes to be uploaded locally
}];
[request setFinishBlock:^(QCloudUploadPartResult* outputObject, NSError *error) {
QCloudMultipartInfo *part = [QCloudMultipartInfo new];
// Retrieve the ETag of the uploaded part
part.eTag = outputObject.eTag;
part.partNumber = @"1";
// Save for use when completing the upload
self.parts = @[part];
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];

}];

[[QCloudCOSXMLService defaultCOSXML] UploadPart:request];
Note
For the complete sample, go to GitHub.
Swift
let uploadPart = QCloudUploadPartRequest<AnyObject>.init();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
uploadPart.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
uploadPart.object = "exampleobject";
uploadPart.partNumber = 1;

// ID of the multipart upload
if let uploadId = self.uploadId {
uploadPart.uploadId = uploadId;
}

// Example file
let dataBody:NSData? = "wrwrwrwrwrwwrwrwrwrwrwwwrwrw"
.data(using: .utf8) as NSData?;

uploadPart.body = dataBody!;
uploadPart.setFinish { (result, error) in
if let result = result {
let mutipartInfo = QCloudMultipartInfo.init();
// Retrieve the ETag of the part
mutipartInfo.eTag = result.eTag;
mutipartInfo.partNumber = "1";
// Save for use when completing the upload
self.parts = [mutipartInfo];
// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}
uploadPart.sendProcessBlock = {(bytesSent,totalBytesSent,
totalBytesExpectedToSend) in
// Upload progress information
// bytesSent Added bytes
// totalBytesSent Total bytes uploaded in this session
// totalBytesExpectedToSend Target number of bytes to be uploaded locally

}
QCloudCOSXMLService.defaultCOSXML().uploadPart(uploadPart);
Note
For the complete sample, go to GitHub.

Querying uploaded parts

Note

This API is used to query the uploaded parts of a specific multipart upload operation.

Sample code

Objective-C
QCloudListMultipartRequest* request = [QCloudListMultipartRequest new];

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
request.object = @"exampleobject";

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
request.bucket = @"examplebucket-1250000000";

// The Initiate Multipart Upload request returns an upload ID used to uniquely identify the upload.
request.uploadId = uploadId;

[request setFinishBlock:^(QCloudListPartsResult * _Nonnull result,
NSError * _Nonnull error) {

// Retrieve the uploaded part information from the result
// Represents the information of each block
NSArray<QCloudMultipartUploadPart*> *parts = result.parts;
}];

[[QCloudCOSXMLService defaultCOSXML] ListMultipart:request];
Note
For the complete sample, go to GitHub.
Swift
let req = QCloudListMultipartRequest.init();

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
req.object = "exampleobject";

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
req.bucket = "examplebucket-1250000000";

// The Initiate Multipart Upload request returns an upload ID used to uniquely identify the upload.
if let uploadId = self.uploadId {
req.uploadId = uploadId;
}
req.setFinish { (result, error) in
if let result = result {
// All completed shards
let parts = result.parts
} else {
print(error!);
}
}

QCloudCOSXMLService.defaultCOSXML().listMultipart(req);
Note
For the complete sample, go to GitHub.

Completing multipart upload

Note

This API (Complete Multipart Upload) is used to complete the multipart upload of an entire file.

Sample code

Objective-C
QCloudCompleteMultipartUploadRequest *completeRequst = [QCloudCompleteMultipartUploadRequest new];
// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
completeRequst.object = @"exampleobject";
// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
completeRequst.bucket = @"examplebucket-1250000000";
// uploadId of the multipart upload to be queried. This ID can be obtained from QCloudInitiateMultipartUploadResult, i.e. the result of the multipart upload initialization request
completeRequst.uploadId = uploadId;
// Information on the uploaded parts
QCloudCompleteMultipartUploadInfo *partInfo = [QCloudCompleteMultipartUploadInfo new];
NSMutableArray * parts = [self.parts mutableCopy];
// Sort the uploaded parts
[parts sortUsingComparator:^NSComparisonResult(QCloudMultipartInfo* _Nonnull obj1,
QCloudMultipartInfo* _Nonnull obj2) {
int a = obj1.partNumber.intValue;
int b = obj2.partNumber.intValue;

if (a < b) {
return NSOrderedAscending;
} else {
return NSOrderedDescending;
}
}];
partInfo.parts = [parts copy];
completeRequst.parts = partInfo;

[completeRequst setFinishBlock:^(QCloudUploadObjectResult * _Nonnull result,
NSError * _Nonnull error) {
// Retrieve the upload result from the result object
// Obtain file CRC64
NSString * crc64 = [[outputObject __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];

[[QCloudCOSXMLService defaultCOSXML] CompleteMultipartUpload:completeRequst];
Note
For the complete sample, go to GitHub.
Swift
let complete = QCloudCompleteMultipartUploadRequest.init();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
complete.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
complete.object = "exampleobject";

// uploadId of the multipart upload to be queried. This ID can be obtained from
// QCloudInitiateMultipartUploadResult, i.e., the result of the multipart copy initialization request
complete.uploadId = "exampleUploadId";
if let uploadId = self.uploadId {
complete.uploadId = uploadId;
}

// Information on the uploaded parts
let completeInfo = QCloudCompleteMultipartUploadInfo.init();
if self.parts == nil {
print("No chunks to complete");
return;
}
if self.parts != nil {
completeInfo.parts = self.parts ?? [];
}

complete.parts = completeInfo;
complete.setFinish { (result, error) in
if let result = result {
// File's etag
let eTag = result.eTag
// Unsigned file link
let location = result.location

// Obtain file CRC64
let crc64 = result?.__originHTTPURLResponse__.allHeaderFields["x-cos-hash-crc64ecma"];
} else {
print(error!);
}
}
QCloudCOSXMLService.defaultCOSXML().completeMultipartUpload(complete);
Note
For the complete sample, go to GitHub.

Aborting a multipart upload

Note

This API (Abort Multipart Upload) is used to abort a multipart upload and delete the uploaded parts.

Sample code

Objective-C
QCloudAbortMultipfartUploadRequest *abortRequest = [QCloudAbortMultipfartUploadRequest new];
// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
abortRequest.object = @"exampleobject";
// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
abortRequest.bucket = @"examplebucket-1250000000";
// uploadId of the multipart upload to be aborted.
// This ID can be obtained from QCloudInitiateMultipartUploadResult, i.e. the result of the multipart upload initialization request
abortRequest.uploadId = @"exampleUploadId";
[abortRequest setFinishBlock:^(id outputObject, NSError *error) {
// You can obtain information such as etag or custom headers from the response in the outputObject.
NSDictionary * result = (NSDictionary *)outputObject;
}];
[[QCloudCOSXMLService defaultCOSXML]AbortMultipfartUpload:abortRequest];
Note
For the complete sample, go to GitHub.
Swift
let abort = QCloudAbortMultipfartUploadRequest.init();

// Bucket name in the format of BucketName-APPID, which can be viewed in the COS console at https://console.cloud.tencent.com/cos5/bucket
abort.bucket = "examplebucket-1250000000";

// Object key, i.e., the full path of a COS object. If the object is in a directory, the path should be "video/xxx/movie.mp4"
abort.object = "exampleobject";

// uploadId of the multipart upload to be queried. This ID can be obtained from
// QCloudInitiateMultipartUploadResult, i.e., the result of the multipart copy initialization request
abort.uploadId = self.uploadId!;

abort.finishBlock = {(result,error)in
if let result = result {
// You can obtain the server's response headers from the result
} else {
print(error!)
}
}
QCloudCOSXMLService.defaultCOSXML().abortMultipfartUpload(abort);
Note
For the complete sample, go to GitHub.