Upload in-memory data directly to OSS—without writing to a local file first—using the put method of the ali-oss Node.js SDK.
Prerequisites
Before you begin, ensure that you have:
An OSS bucket
The
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables set with valid credentialsThe
ali-osspackage installed (npm install ali-oss)The required permissions (see Permissions)
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users and RAM roles have no permissions by default. Grant the required permissions through RAM Policy or Bucket policies.
| API | Action | When required |
|---|---|---|
| PutObject | oss:PutObject | Always required to upload an object |
| PutObject | oss:PutObjectTagging | Required when specifying object tags via x-oss-tagging |
| PutObject | kms:GenerateDataKey, kms:Decrypt | Required when the object metadata includes X-Oss-Server-Side-Encryption: KMS |
Upload from local memory
The following example uploads a Buffer to OSS using the put method.
const OSS = require('ali-oss');
const client = new OSS({
// Set region to the region where your bucket is located.
// Example: oss-cn-hangzhou for the China (Hangzhou) region.
region: 'oss-cn-hangzhou',
// Read credentials from environment variables to avoid hardcoding sensitive values.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
bucket: 'examplebucket',
});
async function putBuffer() {
try {
const result = await client.put('exampledir/exampleobject.txt', Buffer.from('hello world'));
console.log(result);
} catch (e) {
console.log(e);
}
}
putBuffer();Replace the placeholder values before running the example:
| Placeholder | Description | Example |
|---|---|---|
oss-cn-hangzhou | The region where your bucket is located | oss-us-east-1 |
examplebucket | The name of your bucket | my-bucket |
exampledir/exampleobject.txt | The full object key (path and filename) in OSS | uploads/data.json |
References
For the underlying API operation, see PutObject.