Node.js installation
prerequisite
AliCloud OSS service for object storage has been activated. The AccessKey ID and AccessKey Secret of the RAM user have been created. Since the cloud account AccessKey has access to all APIs, it is recommended to use the RAM user's AccessKey. If it is deployed on the server, please use RAM or STS for API access or daily operation and maintenance control operations; If it is deployed on the client side, please use STS mode for API access. For details, see access control 。
background information
install
Usage
async/await
const OSS = require('ali-oss'); //Initialize the OSS client. Please replace the following parameters with your own configuration information. const client = new OSS({ Region: 'yourregion',//Example: 'oss cn hangzhou', fill in the bucket region. AccessKeyId: process.env.OSS_ACCESS_KEY_ID,//Ensure that the environment variable OSS_ACCESS_KEY_ID has been set. AccessKeySecret: process. env. OSS_ACCESS_KEY_SECRET,//Ensure that the environment variable OSS_ACCESS_KEY_SECRET has been set. Bucket: 'yourbucketname',//Example: 'my bucket name', fill in the name of the storage space. }); async function uploadAndDownloadFile() { try { //Upload a file to OSS. 'object' is the file name in OSS, and 'localfile' is the path of the local file. const uploadResult = await client.put('object', 'localfile'); Console. log ('Upload succeeded: ', uploadResult); //Download files from OSS to verify that the upload is successful. const getResult = await client.get('object'); Console. log ('Getting the file succeeded: ', getResult); } catch (error) { Console. error ('Error occurred: ', error); //Add error handling logic here. } } uploadAndDownloadFile();
then/catch
const OSS = require('ali-oss'); //Initialize the OSS client. Please replace the following parameters with your own configuration information. const client = new OSS({ Region: 'yourregion',//Example: 'oss cn hangzhou', fill in the bucket region. AccessKeyId: process.env.OSS_ACCESS_KEY_ID,//Ensure that the environment variable OSS_ACCESS_KEY_ID has been set. AccessKeySecret: process. env. OSS_ACCESS_KEY_SECRET,//Ensure that the environment variable OSS_ACCESS_KEY_SECRET has been set. Bucket: 'yourbucketname',//Example: 'my bucket name', fill in the name of the storage space. }); //Upload the file using the OSS put method, and then call then in a chained way to process the results or catch errors. client.put('object', 'localfile') .then((uploadResult) => { Console. log ('Upload succeeded: ', uploadResult); //Continue downloading the file to verify that the upload was successful. return client.get('object'); }) .then((getResult) => { Console. log ('Getting the file succeeded: ', getResult); }) .catch((error) => { Console. error ('Error occurred: ', error); //Add error handling logic here. });