All Products
Search
Document Center

Object Storage Service:Simple file downloads from OSS

Last Updated:Nov 27, 2025

A simple download calls the GetObject operation of the Object Storage Service (OSS) API to download an object. This method is suitable for downloading an object in a single HTTP request.

Prerequisites

  • An object has been uploaded to OSS. For more information, see Upload objects.

  • If you want to download an Archive object, ensure that the object is in the restored state or that real-time access of Archive objects is enabled for the bucket. For more information, see Restore objects and real-time access of Archive objects.

  • If you want to download a Cold Archive or Deep Cold Archive object, ensure that the object is in the restored state. For more information, see Restore objects.

Methods

Important

Due to a policy adjustment to improve OSS compliance and security, new users who activate OSS after March 20, 2025 cannot use default public endpoints to call data API operations, such as uploading or downloading files, for buckets in the Chinese mainland. You must use a custom domain name (CNAME) to access OSS. If you use HTTPS to access OSS, such as in the console, you must also configure an SSL certificate for the custom domain name.

Use the OSS console

Note

You cannot download a directory or its subdirectories from the OSS console. To download a directory or its subdirectories, you can use ossbrowser, ossutil, an SDK, or an API operation.

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Object Management > Objects.

  4. Download objects.

    • Download a single object

      Method 1: In the Actions column of the target object, choose more > Download.

      Note

      If you moved this operation from the default Added to More section to the Common Object Operations section, you can view the operation without clicking the more icon.

      Method 2: Click the name of the target object or click View Details in the Actions column. In the Detail panel that appears, click Download.

    • Download multiple objects

      Select multiple objects and click Download at the bottom of the list. You can download up to 100 objects at a time from the OSS console.

Use the ossbrowser GUI

ossbrowser provides object-level operations similar to those in the OSS console. You can follow the instructions in the ossbrowser UI to download an object. For more information, see Common operations.

Use Alibaba Cloud SDKs

The following code provides examples of how to perform a simple download using common SDKs. For information about how to perform this download using other SDKs, see SDK overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt.
        String objectName = "testfolder/exampleobject.txt";
        // Specify the full path of the local file to which you want to download the object.
        String pathName = "D:\\localpath\\examplefile.txt";
        // 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 cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Download the object to the specified path. If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path.
            // If you do not specify the local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs.
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}   
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(); 
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <!-- Import the SDK file -->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      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",
        authorizationV4: true,
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // Specify the security token obtained from STS. 
        stsToken: "yoursecurityToken",
        // Specify the name of the bucket. 
        bucket: "examplebucket",
      });

      // Set the response header to automatically download an object by using the URL, and set the name of the local file after the object is downloaded. 
      const filename = "examplefile.txt";
      const response = {
        "content-disposition": `attachment; filename=${encodeURIComponent(
          filename
        )}`,
      };
      // Specify the full path of the object. Do not include the bucket name in the full path. 
      const url = client.signatureUrl("exampleobject.txt", { response });
      console.log(url);
    </script>
  </body>
</html>
// Construct an object download request. 
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
GetObjectRequest get = new GetObjectRequest("examplebucket", "exampledir/exampleobject.txt");

oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
    @Override
    public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// Start reading data. 
        long length = result.getContentLength();
        if (length > 0) {
            byte[] buffer = new byte[(int) length];
            int readCount = 0;
            while (readCount < length) {
                try{
                    readCount += result.getObjectContent().read(buffer, readCount, (int) length - readCount);
                }catch (Exception e){
                    OSSLog.logInfo(e.toString());
                }
            }
    // Specify the full path of the downloaded object. Example: D:\\localpath\\exampleobject.jpg. 
            try {
                FileOutputStream fout = new FileOutputStream("download_filePath");
                fout.write(buffer);
                fout.close();
            } catch (Exception e) {
                OSSLog.logInfo(e.toString());
            }
        }
    }

    @Override
    public void onFailure(GetObjectRequest request, ClientException clientException,
                          ServiceException serviceException)  {

    }
});
OSSGetObjectRequest * request = [OSSGetObjectRequest new];

// Specify the name of the bucket. Example: examplebucket. 
request.bucketName = @"examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
request.objectKey = @"exampledir/exampleobject.txt";

// Configure optional fields. 
request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
    // Specify the number of bytes that are being downloaded, the number of bytes that are downloaded, and the total number of bytes that you want to download. 
    NSLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
};
// request.range = [[OSSRange alloc] initWithStart:0 withEnd:99]; // bytes=0-99. Specify that the download range is from byte 0 to byte 99. 
// request.downloadToFileURL = [NSURL fileURLWithPath:@"<filepath>"]; // If you need to directly download the object to a file, specify the path of the file. 

OSSTask * getTask = [client getObject:request];

[getTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"download object success!");
        OSSGetObjectResult * getResult = task.result;
        NSLog(@"download result: %@", getResult.downloadedData);
    } else {
        NSLog(@"download object failed, error: %@" ,task.error);
    }
    return nil;
}];

// [getTask waitUntilFinished];

// [request cancel];
#include <alibabacloud/oss/OssClient.h>
#include <memory>
#include <fstream>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* 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 cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";
    /* Download the object as a local file named examplefile.txt and save the file to D:\\localpath. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. */
    /* If you do not specify the path of the local file, the downloaded object is saved to the path of the project to which the sample program belongs. */
    std::string FileNametoSave = "D:\\localpath\\examplefile.txt";

    /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Download the object as a local file. */
    GetObjectRequest request(BucketName, ObjectName);
    request.setResponseStreamFactory([=]() {return std::make_shared<std::fstream>(FileNametoSave, std::ios_base::out | std::ios_base::in | std::ios_base::trunc| std::ios_base::binary); });

    auto outcome = client.GetObject(request);

    if (outcome.isSuccess()) {    
        std::cout << "GetObjectToFile success" << outcome.result().Metadata().ContentLength() << std::endl;
    }
    else {
        /* Handle exceptions. */
        std::cout << "GetObjectToFile fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";

/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify the full path of the local file. */
const char *local_filename = "yourLocalFilename";
/* 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 cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */    
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Specify two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Specify network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_string_t file;
    aos_table_t *params;
    aos_table_t *headers = NULL;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    aos_str_set(&file, local_filename);
    params = aos_table_make(pool, 0);
    /* Download the object to your local file. If a file with the same name already exists, the downloaded object overwrites the file. Otherwise, a new file is created. */
    resp_status = oss_get_object_to_file(oss_client_options, &bucket, &object, headers, params, &file, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("Get object from file succeeded\n");
    } else {
        printf("Get object from file failed\n");
    }  
    /* Release the memory pool. This operation releases memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# Download the object to your local computer. 
bucket.get_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')
package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Use the init function to initialize parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse parameters.
	flag.Parse()

	// Check whether the bucket name is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Specify the path of the local file.
	localFile := "download.file"

	// For example, an object was last modified at 18:43:02, November 21, 2023. If the time specified in the IfModifiedSince condition is earlier than the last modified time, the object is downloaded.
	date := time.Date(2024, time.October, 21, 18, 43, 2, 0, time.UTC)

	// Assume that the ETag of an object is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. If the ETag specified in the IfMatch condition matches the ETag of the object, the object is downloaded.
	etag := "\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\""

	// Create a request to download the object.
	getRequest := &oss.GetObjectRequest{
		Bucket:          oss.Ptr(bucketName),                   // The name of the bucket.
		Key:             oss.Ptr(objectName),                   // The name of the object.
		IfModifiedSince: oss.Ptr(date.Format(http.TimeFormat)), // Specify the IfModifiedSince condition.
		IfMatch:         oss.Ptr(etag),                         // Specify the IfMatch condition.
	}

	// Download the object to a local device and process the result.
	result, err := client.GetObjectToFile(context.TODO(), getRequest, localFile)
	if err != nil {
		log.Fatalf("failed to get object to file %v", err)
	}

	log.Printf("get object to file result:%#v\n", result)
}
import argparse
import alibabacloud_oss_v2 as oss
import os

# Create a command line argument parser
parser = argparse.ArgumentParser(description="get object sample")

# Specify the --region parameter, which specifies the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configuration of the SDK and specify the credential provider
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region in the configuration
    cfg.region = args.region

    # If an endpoint is provided, specify the endpoint in the configuration object
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance
    client = oss.Client(cfg)

    # Execute the request to download the object, and specify the bucket name and object name
    result = client.get_object(oss.GetObjectRequest(
        bucket=args.bucket,  # Specify the bucket name
        key=args.key,  # Specify the object key
    ))

    # Display the response to check whether the request is successful
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content length: {result.content_length},'
          f' content range: {result.content_range},'
          f' content type: {result.content_type},'
          f' etag: {result.etag},'
          f' last modified: {result.last_modified},'
          f' content md5: {result.content_md5},'
          f' cache control: {result.cache_control},'
          f' content disposition: {result.content_disposition},'
          f' content encoding: {result.content_encoding},'
          f' expires: {result.expires},'
          f' hash crc64: {result.hash_crc64},'
          f' storage class: {result.storage_class},'
          f' object type: {result.object_type},'
          f' version id: {result.version_id},'
          f' tagging count: {result.tagging_count},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' next append position: {result.next_append_position},'
          f' expiration: {result.expiration},'
          f' restore: {result.restore},'
          f' process status: {result.process_status},'
          f' delete marker: {result.delete_marker},'
    )

    # ========== Method 1: Read the entire content ==========
    with result.body as body_stream:
        data = body_stream.read()
        print(f"The object is read. Data length: {len(data)} bytes")

        path = "./get-object-sample.txt"
        with open(path, 'wb') as f:
            f.write(data)
        print(f"The object is downloaded and saved to a local path: {path}")

    # # ========== Method 2: Read by blocks ==========
    # with result.body as body_stream:
    #     chunk_path = "./get-object-sample-chunks.txt"
    #     total_size = 0

    #     with open(chunk_path, 'wb') as f:
    #         # Use a 256KB block size (you can adjust the block_size parameter as needed)
    #         for chunk in body_stream.iter_bytes(block_size=256 * 1024):
    #             f.write(chunk)
    #             total_size += len(chunk)
    #             print(f"Data block received: {len(chunk)} bytes | Total: {total_size} bytes")

    #     print(f"The object is downloaded and saved to a local path: {chunk_path}")

# Call the main function when the script is directly run
if __name__ == "__main__":
    main()  # Script entry point, calls the main function when the file is directly run
<?php

// Introduce autoload files to load dependency libraries
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the parameter
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if the required parameters are not configured.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket
$key = $options["key"];       // The name of the object

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.    
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);

// Query the object.
$result = $client->getObject($request);

// Specify the local path to save the object.
$localFilePath = 'path/to/local/file.txt'; // Replace with the actual file path

// Write the content to the local file.
file_put_contents( $localFilePath, $result->body->getContents());

// Display the result.
// Output the HTTP status code, request ID, and content of the object.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // HTTP status code, such as 200 for success
    'request id:' . $result->requestId . PHP_EOL  // Request ID for debugging or tracking requests
);

Use the ossutil command line interface

You can use the ossutil command line interface (CLI) to download files. For more information about how to install ossutil, see Install ossutil.

The following command downloads the exampleobject file from the examplebucket bucket.

ossutil api get-object --bucket examplebucket --key exampleobject

For more information about this command, see get-object.

Related API operations

The preceding methods are built on API operations. For advanced customization, you can call the RESTful API directly. Calling the API directly requires you to manually write code to calculate signatures. For more information, see GetObject.

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

GetObject

oss:GetObject

Downloads an object.

oss:GetObjectVersion

When downloading an object, if you specify the object version through versionId, this permission is required.

kms:Decrypt

When downloading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, this permission is required.

Billing

The following billable items apply to simple downloads. For more information about the unit price of the billable items, see Object Storage Service pricing.

API

Billable item

Description

GetObject

GET requests

You are charged request fees based on the number of successful requests.

Outbound traffic over the Internet

If you call the GetObject operation by using a public endpoint, such as oss-cn-hangzhou.aliyuncs.com, or an acceleration endpoint, such as oss-accelerate.aliyuncs.com, you are charged fees for outbound traffic over the Internet based on the data size.

Retrieval of IA objects

If IA objects are retrieved, you are charged IA data retrieval fees based on the size of the retrieved IA data.

Retrieval of Archive objects in a bucket for which real-time access is enabled

If you retrieve Archive objects in a bucket for which real-time access is enabled, you are charged Archive data retrieval fees based on the size of retrieved Archive objects.

Transfer acceleration fees

If you enable transfer acceleration and use an acceleration endpoint to access your bucket, you are charged transfer acceleration fees based on the data size.

References

  • For more information about how to download an object from a versioning-enabled bucket, see Manage objects in a versioning-enabled bucket.

  • For more information about how to download an object from a versioning-suspended bucket, see Manage objects in a versioning-suspended bucket.

  • OSS provides bucket-level and object-level access control to prevent unauthorized users from downloading data from your buckets. For more information, see Overview of permissions and access control.

  • If you want to resume an interrupted download of a large object, you can use resumable download. For more information, see Resumable download.

  • If you want to authorize a third party to download objects from your private bucket, you can use temporary access credentials from Security Token Service (STS) or a signed URL. For more information, see Authorize a third party to download objects.

  • If you want to download an object only when specific conditions are met, you can specify conditions for the download. An error is returned if the conditions are not met. For more information, see Conditional download.