Download an object from an OSS bucket directly to memory or to a local file using the OSS SDK for HarmonyOS.
Note This guide covers direct programmatic downloads. To generate a download link for browser or end-user access, use a pre-signed URL instead. For more information, see Authorized access.
Prerequisites
Before you begin, ensure that you have:
The
oss:GetObjectpermission on the target bucket. For more information, see Grant custom permissions to a RAM userThe endpoint for the region where the bucket is located. For more information, see OSS regions and endpoints
Download to memory
Use getObject without a writeStream to receive the object content as an ArrayBuffer in res.data.
import Client, { RequestError } from '@aliyun/oss';
const client = new Client({
accessKeyId: 'yourAccessKeyId', // AccessKey ID obtained from Security Token Service (STS)
accessKeySecret: 'yourAccessKeySecret', // AccessKey secret obtained from STS
securityToken: 'yourSecurityToken', // STS token obtained from STS
region: 'oss-cn-hangzhou', // Region where the bucket is located
});
const bucket = 'yourBucketName';
const key = 'yourObjectName';
const getObject = async () => {
try {
const res = await client.getObject({ bucket, key });
// res.data contains the object content as an ArrayBuffer
const buf: ArrayBuffer = res.data!;
console.log(JSON.stringify(res));
} catch (err) {
if (err instanceof RequestError) {
console.log('High-level error code: ', err.code);
console.log('message: ', err.message);
console.log('Request ID: ', err.requestId);
console.log('HTTP status code: ', err.status);
console.log('Fine-grained error code: ', err.ec);
} else {
console.log('unknown error: ', err);
}
}
};
getObject();Replace the placeholders before running:
| Placeholder | Description | Example |
|---|---|---|
yourAccessKeyId | AccessKey ID obtained from STS | LTAI5tXxx |
yourAccessKeySecret | AccessKey secret obtained from STS | xXxXxXxx |
yourSecurityToken | STS token obtained from STS | — |
oss-cn-hangzhou | Region where the bucket is located | oss-cn-hangzhou |
yourBucketName | Name of the bucket | examplebucket |
yourObjectName | Key of the object to download | images/photo.jpg |
该文章对您有帮助吗?