This topic describes the simple upload method, which is a straightforward way to quickly upload a single file to OSS.
Precautions
For more information about the regions and endpoints that OSS supports, see Regions and endpoints.
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM Policy or Bucket policies.
API | Action | Definition |
PutObject |
| Uploads an object. |
| When uploading an object, if you specify object tags through | |
| When uploading an object, if the object metadata contains | |
|
Sample code
You can use the following code to upload a string as a file to the destination bucket.
If you upload an object to a bucket that already contains an object with the same name, the new object overwrites the existing object if you have the required access permissions.
import Client, { RequestError } from '@aliyun/oss';
// Create an OSS client instance.
const client = new Client({
// Replace with the Access Key ID of the STS temporary access credential.
accessKeyId: 'yourAccessKeyId',
// Replace with the Access Key Secret of the STS temporary access credential.
accessKeySecret: 'yourAccessKeySecret',
// Replace with the security token of the STS temporary access credential.
securityToken: 'yourSecurityToken',
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
});
const bucket = 'yourBucketName'; // Replace with the name of the bucket you want to use.
const key = 'yourObjectName'; // Replace with the name of the object (file) you want to upload.
const putObject = async () => {
try {
// Call the putObject method to upload data to the specified bucket and key, passing the data as a parameter.
const res = await client.putObject({
bucket, // The bucket name.
key, // The object (file) name.
data: 'hello world' // The data to upload. In this case, a simple string.
});
// Print the upload result.
console.log(JSON.stringify(res));
} catch (err) {
// Catch exceptions that occur during the request.
if (err instanceof RequestError) {
// If the error is a known type, print the error code, message, request ID, status code, EC code, and other information.
console.log('code: ', err.code);
console.log('message: ', err.message);
console.log('requestId: ', err.requestId);
console.log('status: ', err.status);
console.log('ec: ', err.ec);
} else {
// Print other unknown types of errors.
console.log('unknown error: ', err);
}
}
}
// Call the putObject function to perform the upload operation.
putObject();