All Products
Search
Document Center

Object Storage Service:Download objects as files

Last Updated:Oct 18, 2023

This topic describes how to download an object from a bucket to your computer.

Sample code

The following sample code provides an example on how to download an object named exampleobject.txt in a bucket named examplebucket to the D:\localpath path in a local disk:

const OSS = require('ali-oss');

const client = new OSS({
  // 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: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
});

async function get () {
  try {
    // Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object. 
    // If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved as a local file. 
    // If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
    const result = await client.get('exampleobject.txt', 'D:\\localpath\\examplefile.txt');
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

get(); 

References

  • For the complete sample code that is used to download objects to your computer, visit GitHub.

  • For more information about the API operation that you can call to download an object as a local file, see GetObject.