This topic describes how to quickly upload a local file to Object Storage Service (OSS) using simple upload. This method is straightforward and suitable for scenarios where you need to quickly upload a local file.
Considerations
For more information about the mapping between regions and endpoints supported by OSS, see OSS 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 Policy.
API | Action | Definition |
PutObject |
| Uploads an object. |
| When uploading an object, if you specify object tags through x-oss-tagging, this permission is required. | |
| When uploading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, these two permissions are required. | |
|
Sample code
The following sample code demonstrates how to upload a simple string to a bucket:
If you upload an object with the same name as an accessible existing object, the existing object will be overwritten by the uploaded object.
import Client, { RequestError } from '@aliyun/oss';
// Create an OSS client instance
const client = new Client({
// Specify the AccessKey ID obtained from STS
accessKeyId: 'yourAccessKeyId',
// Specify the AccessKey secret obtained from STS
accessKeySecret: 'yourAccessKeySecret',
// Specify the security token obtained from STS
securityToken: 'yourSecurityToken',
// Specify the region in which 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',
});
const bucket = 'yourBucketName'; // Specify the name of the bucket
const key = 'yourObjectName'; // Specify the name of the object
const putObject = async () => {
try {
// Use the putObject method to upload data to object in the specified bucket and pass parameters
const res = await client.putObject({
bucket, // Specify the name of the bucket
key, // Specify the name of the object
data: 'hello world' // Specify the data that you want to upload. In this example, a simple string is uploaded
});
// Display the result of the simple upload request
console.log(JSON.stringify(res));
} catch (err) {
// Capture the 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('code: ', err.code);
console.log('message: ', err.message);
console.log('requestId: ', err.requestId);
console.log('status: ', err.status);
console.log('ec: ', err.ec);
} else {
// Display other unknown types of errors
console.log('unknown error: ', err);
}
}
}
// Call the putObject function to perform the object upload operation
putObject();