Feature Overview
Note
This API is used to read the object content. If you need to launch a browser to download the file, you can get the URL through cos.getObjectUrl and then start a download in the browser. For more information, see Pre-signed URL.
This document provides an overview of APIs and SDK code samples for downloading an object.
API | Operation | Description |
Downloading object | Downloads an object to the local file system |
Note
The GET Object API request can retrieve the content of a specified file in the bucket, with the file content in string format. To download the file to your local machine, please refer to Pre-signed URL.
Downloading a single object
Use Cases
cos.getObject({Bucket: 'examplebucket-1250000000', /* Enter your own bucket, required field */Region: 'COS_REGION', /* The region where the bucket is located, such as ap-beijing, required field */Key: '1.jpg', /* The object key stored in the bucket (e.g., 1.jpg, a/b/test.txt), required field */onProgress: function (progressData) {console.log(JSON.stringify(progressData));}}, function(err, data) {console.log(err || data.Body);});
Get the file content with
Range specified:cos.getObject({Bucket: 'examplebucket-1250000000', /* Enter your own bucket, required field */Region: 'COS_REGION', /* The region where the bucket is located, such as ap-beijing, required field */Key: '1.jpg', /* The object key stored in the bucket (e.g., 1.jpg, a/b/test.txt), required field */Range: 'bytes=1-3', /* Optional */onProgress: function (progressData) {console.log(JSON.stringify(progressData));}}, function(err, data) {console.log(err || data.Body);});
Object content in BLOB format is returned.
cos.getObject({Bucket: 'examplebucket-1250000000', /* Required */Region: 'COS_REGION', /* The region where the bucket is located, required field */Key: 'exampleobject', /* Required */DataType: 'blob', /* Optional */onProgress: function (progressData) {console.log(JSON.stringify(progressData));}}, function(err, data) {console.log(err || data.Body);});
Downloading an object (limiting single-URL speed):
Note
For more information about the speed limits on object downloads, see Single-Connection Bandwidth Limit.
cos.getObject({Bucket: 'examplebucket-1250000000', /* Enter your own bucket, required field */Region: 'COS_REGION', /* The region where the bucket is located, such as ap-beijing, required field */Key: '1.jpg', /* The object key stored in the bucket (e.g., 1.jpg, a/b/test.txt), required field */Headers: {'x-cos-traffic-limit': 819200, // The valid range for the limit value is 819,200 - 838,860,800, with the default unit being bit/s, i.e., 800Kb/s - 800Mb/s. If it exceeds this range, a 400 error will be returned.},onProgress: function (progressData) {console.log(JSON.stringify(progressData));}}, function(err, data) {console.log(err || data.Body);});
Description
Parameter | ParameterDescription | Local Disk Types | Required |
Bucket | Bucket name in the format of BucketName-APPID. | String | Required |
Region | String | Required | |
Key | Object key (object name), the unique identifier of an object in a bucket. For more information, see Object Overview. | String | Required |
DataType | Format of the object content returned. Enumerated values: string (default), blob, arraybuffer | String | Not required |
ResponseContentType | Sets the Content-Type parameter in the response header. | String | Not required |
ResponseContentLanguage | Sets the Content-Language parameter in the response header. | String | Not required |
ResponseExpires | Sets the Content-Expires parameter in the response header. | String | Not required |
ResponseCacheControl | Sets the Cache-Control parameter in the response header. | String | Not required |
ResponseContentDisposition | Sets the Content-Disposition parameter in the response header. | String | Not required |
ResponseContentEncoding | Sets the Content-Encoding parameter in the response header. | String | Not required |
Range | Byte range of the object as defined in RFC 2616. The range value must be in the format of bytes=first-last, where both first and last are offsets starting from 0. For example, bytes=0-9 means that you want to copy the first 10 bytes of data of the source object. If this parameter is not specified, the entire object will be downloaded. | String | Not required |
IfModifiedSince | If the object is modified after the specified time, the object will be returned; otherwise, "304 (Not Modified)" will be returned. | String | Not required |
IfUnmodifiedSince | If the object is not modified after the specified time, the object will be returned; otherwise, HTTP status 412 (precondition failed) will be returned | String | Not required |
IfMatch | The object will be returned only if the value of ETag matches the specified value; otherwise, 412 (precondition failed) will be returned. | String | Not required |
IfNoneMatch | The object will be returned only if the value of ETag does not match the specified value; otherwise, "304 (not modified)" will be returned. | String | Not required |
VersionId | Version ID of the object to download | String | Not required |
onProgress | Progress callback function. Attributes of the progress callback response object, progressData, are as follows | Function | Not required |
- progressData.loaded | Size of the downloaded parts, in bytes | Number | Not required |
- progressData.total | Size of the entire object, in bytes | Number | Not required |
- progressData.speed | Download speed, in bytes/s | Number | Not required |
- progressData.percent | Percentage of the file download progress, in decimal form. For example, 0.5 means 50% has been downloaded. | Number | Not required |
Callback function description
function(err, data) { ... }
Parameter | ParameterDescription | Local Disk Types |
err | Error code, which is returned when an error (network error or service error) occurs. If the request is successful, this parameter is empty. For more information, see Error Codes. | Object |
- statusCode | HTTP status code, such as 200, 403, and 404 | Number |
- headers | Returned headers | Object |
data | Object returned when the request is successful. If the request fails, this parameter is empty. | Object |
- statusCode | HTTP status code returned by the request, such as 200, 304, 403, and 404 | Number |
- headers | Returned headers | Object |
- CacheControl | Cache directives as defined in RFC 2616. It will be returned only if it is contained in the object metadata or specified through the request parameter. | String |
- ContentDisposition | Filename as defined in RFC 2616. It will be returned only if it is contained in the object metadata or specified through the request parameter. | String |
- ContentEncoding | Encoding format as defined in RFC 2616, which will be returned only if it is contained in the object metadata or if it is specified in the request parameter | String |
- Expires | Cache expiration time as defined in RFC 2616, which will be returned only if it is contained in the object metadata or if it is specified in the request parameter | String |
- x-cos-storage-class | The storage type of the object, with enumeration values: STANDARD, STANDARD_IA. For more storage types, see Storage Class Overview. Note: If this header is not returned, it indicates that the file storage type is STANDARD (standard storage). | String |
- x-cos-meta-* | User defined metadata | String |
- NotModified | This attribute will be returned if the request contains IfModifiedSince. If the file has been modified, false will be returned. If not, true will be returned. | Boolean |
- ETag | Returns the MD5 checksum value of the file. The ETag value can be used to verify whether the object has been damaged during the upload or download process. For example, "09cba091df696af91549de27b8e7d0f6". Note: The ETag value here is enclosed in double quotes. | String |
- VersionId | Version ID of the object to download | String |
- Body | Returned file content, in string format by default | String |
Downloading multiple objects
Note
Not recommended for use, as it does not allow for programmatic control over starting and stopping the download. When downloading multiple objects, this may result in a suboptimal user experience.
Use Cases
Downloading multiple objects with a specified prefix (downloading files in a specified directory):
var getObjects = function (marker) {cos.getBucket({Bucket: config.Bucket,Region: config.Region,Prefix: 'abc', /* The directory to download, or the prefix of the files to download */Marker: marker,MaxKeys: 1000,}, function (listError, listResult) {if (listError) return console.log('list error:', listError);var nextMarker = listResult.NextMarker;listResult.Contents.forEach(function (item) {cos.getObjectUrl({Bucket: config.Bucket,Region: config.Region,Key: item.Key,}, function(err, data) {if (err) return console.log(err);setTimeout(() => {var downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'response-content-disposition=attachment'; // Add the parameter for forced downloadwindow.open(downloadUrl); // This opens the URL in a new window. If you need to open it in the current window, you can use a hidden iframe to download or use the "a" tag with the download attribute to assist in downloading.}, 500);});});// If not all files have been processed, continue to query the next page of the file listif (listResult.IsTruncated === 'true') getMultipleObjects(nextMarker);});}getObjects();