Simple download (Harmony SDK)
Updated at:
This topic describes how to quickly download an object from an Object Storage Service (OSS) bucket to a local device.
Considerations
-
For information about the mapping between regions and endpoints supported by OSS, see OSS regions and endpoints.
-
To download an object to a local device, you must have the
oss:GetObjectpermission. For more information, see Grant custom permissions to a RAM user.
Sample code
The following code shows how to download an object from a bucket to local memory.
import Client, { RequestError } from '@aliyun/oss';
// Create an OSS client instance.
const client = new Client({
// Specify the AccessKey ID obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
// Specify the AccessKey secret obtained from STS.
accessKeySecret: 'yourAccessKeySecret',
// Specify the STS token obtained from STS.
securityToken: 'yourSecurityToken',
// Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
});
// Specify the name of the bucket.
const bucket = 'yourBucketName';
// Specify the name of the object that you want to download.
const key = 'yourObjectName';
/**
* Download an object.
* Use the getObject method to download an object from the specified bucket and key. The object content is returned through res.data as an ArrayBuffer.
*/
const getObject = async () => {
try {
// Call the getObject method to download the object from the specified bucket and key.
const res = await client.getObject({
bucket, // Specify the name of the bucket.
key, // Specify the name of the object.
});
// Query the content of the object. The data type is ArrayBuffer.
const buf: ArrayBuffer = res.data!;
// Display the result of the object download operation.
console.log(JSON.stringify(res));
} catch (err) {
// Capture exceptions during the request.
if (err instanceof RequestError) {
// For a known error, display the error codes, error message, requests ID, and HTTP status code.
console.log('High-level error code: ', err.code); // Display the high-level error code.
console.log('message: ', err.message); // Display the error message.
console.log('Request ID: ', err.requestId); // Display the request ID.
console.log('HTTP status code: ', err.status); // Display the HTTP status code.
console.log('Fine-grained error code: ', err.ec); // Display the fine-grained error code.
} else {
// Display other unknown types of errors.
console.log('unknown error: ', err);
}
}
};
// Call the getObject function to download the object.
getObject();
Common scenarios
Is this page helpful?