All Products
Search
Document Center

Object Storage Service:Download objects

Last Updated:Oct 19, 2023

By default, when you call the GetObject operation on an object in a versioning-enabled bucket, only the current version of the object is returned.

Background information

When you call the GetObject operation to download an object in a bucket, you may obtain one of the following results:

  • If the current version of the object is a delete marker, OSS returns 404 Not Found.

  • If a version ID of the object is specified in the request, OSS returns the specified version of the object. If the version ID is set to null in the request, OSS returns the version whose version ID is null.

  • If the version ID specified in the request is the version ID of a delete marker, OSS returns 405 Method Not Allowed.

Sample code

The following code provides an example on how to download an object:

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: 'yourbucketname'
});

async function get() {
  // Specify the name of the object. 
  const result = await client.get('filename', {    
      // Display the version ID of the downloaded object. 
      versionId: 'versionid',
  });
  console.log(result.content);
}
get();

References

For more information about the API operation that you can call to download an object, see GetObject.