Tous les produits
Search
Centre de documentation

Object Storage Service:Téléchargement simple d'un fichier OSS

Dernière mise à jour :Aug 18, 2026

Le téléchargement simple utilise l'opération API GetObject pour télécharger un objet en une seule requête HTTP.

Prérequis

  • Les objets sont chargés dans OSS. Pour plus d'informations, consultez la rubrique Chargement d'objets.

  • Pour télécharger un objet de classe de stockage Archive, assurez-vous que l'objet est restauré ou que la fonctionnalité Archive Direct Read est activée pour le bucket. Pour plus d'informations, consultez la rubrique Restauration d'objets.

  • Pour télécharger un objet des classes de stockage Cold Archive ou Deep Cold Archive, vous devez d'abord le restaurer. Pour plus d'informations, consultez la rubrique Restauration d'objets.

Méthodes

Important

Suite à un changement de politique visant à améliorer la conformité et la sécurité, les nouveaux utilisateurs OSS doivent, à compter du 20 mars 2025, utiliser un nom de domaine personnalisé (CNAME) pour exécuter des opérations d'API de données sur les buckets OSS situés dans les régions de Chine continentale. Les endpoints publics par défaut sont restreints pour ces opérations. Consultez l'annonce officielle pour obtenir la liste complète des opérations concernées. Si vous accédez à vos données via HTTPS, vous devez associer un certificat SSL valide à votre nom de domaine personnalisé. Cette étape est obligatoire pour l'accès à la console OSS, car la console impose l'utilisation du protocole HTTPS.

Console OSS

Remarque

Il est impossible de télécharger un répertoire, y compris ses sous-répertoires, depuis la console OSS. Pour télécharger un répertoire, utilisez des outils tels qu'ossbrowser, ossutil, un SDK OSS ou des opérations API.

  1. Connectez-vous à la console OSS.

  2. Dans le volet de navigation de gauche, cliquez sur Buckets. Sur la page qui s'affiche, cliquez sur le nom du bucket cible.

  3. Dans le volet de navigation de gauche, choisissez Object Management > Objects.

  4. Téléchargez un ou plusieurs objets.

    • Téléchargement d'un objet unique

      Méthode 1 : Dans la colonne Actions de l'objet cible, choisissez more > Download.

      Remarque

      Si vous avez déplacé cette opération de la section par défaut Added to More vers la section Common Operations, vous pouvez cliquer directement sur l'option sans développer l'icône more.

      Méthode 2 : Cliquez sur le nom de l'objet cible ou sur View Details dans la colonne Actions. Dans le panneau Detail qui s'affiche, cliquez sur Download.

    • Téléchargement de plusieurs objets

      Sélectionnez plusieurs objets et cliquez sur Download. Vous pouvez télécharger jusqu'à 100 objets simultanément depuis la console OSS.

ossbrowser

ossbrowser prend en charge des opérations au niveau des objets similaires à celles de la console OSS. Suivez les instructions affichées dans le client ossbrowser pour effectuer un téléchargement simple. Pour plus d'informations sur l'utilisation d'ossbrowser, consultez la rubrique Opérations courantes.

SDK OSS

Les sections suivantes fournissent des exemples de code pour effectuer un téléchargement simple à l'aide des SDK OSS pour les langages de programmation courants. Pour plus d'informations sur les téléchargements simples utilisant d'autres SDK OSS, consultez la rubrique Présentation des SDK.

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 your 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,
  authorizationV4: true,
  // 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 empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

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

	// Check whether the object name is empty.
	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")

# Add the --region command-line argument to specify the region in which the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument to specify the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument to specify the domain name that other services can use to access OSS. This argument is not required.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument to specify the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

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

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and set the credentials 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, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configured information to create an OSS client.
    client = oss.Client(cfg)

    # Execute a request to get the object. 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.
    ))

    # Print the result of getting the object 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 object ==========
    with result.body as body_stream:
        data = body_stream.read()
        print(f"The file is read. Data length: {len(data)} bytes")

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

    # # ========== Method 2: Read in chunks ==========
    # 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 256 KB block size. You can change the block_size parameter based on your needs.
    #         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 file is downloaded and saved to the path: {chunk_path}")

# When this script is run directly, the main function is called.
if __name__ == "__main__":
    main()  # The entry point of the script. When the file is run directly, the main function is called.
<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Convert the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether the required parameters exist.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the parameter.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required parameter is missing, exit the program.
    }
}

// Extract values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key 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 credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client 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);

// Execute the get object operation.
$result = $client->getObject($request);

// Define the path of the local file to be saved.
$localFilePath = 'path/to/local/file.txt'; // Replace it with the actual file path.

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

// Print the result.
// Output the HTTP status code, request ID, and object content.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL  // The request ID, which is used for debugging or tracking requests.
);

CLI ossutil

Utilisez l'outil de ligne de commande ossutil pour télécharger des objets. Pour savoir comment installer ossutil, consultez la rubrique Installation d'ossutil.

La commande suivante télécharge l'objet exampleobject depuis le bucket examplebucket.

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

Pour plus d'informations sur cette commande, consultez la rubrique get-object.

Référence API

Les méthodes décrites dans cette rubrique reposent sur l'opération API GetObject. Pour une personnalisation avancée, appelez directement l'opération API REST GetObject, ce qui nécessite de calculer manuellement la signature. Pour plus d'informations, consultez la rubrique GetObject.

Autorisations

Par défaut, un compte Alibaba Cloud dispose de toutes les autorisations. Les utilisateurs RAM ou les rôles RAM associés à un compte Alibaba Cloud ne disposent d'aucune autorisation par défaut. Le compte Alibaba Cloud ou l'administrateur du compte doit accorder les autorisations d'opération via des politiques RAM ou une Bucket Policy.

API

Action

Description

GetObject

oss:GetObject

Télécharge un objet.

oss:GetObjectVersion

Lors du téléchargement d'un objet, si vous spécifiez la version de l'objet via versionId, cette autorisation est requise.

kms:Decrypt

Lors du téléchargement d'un objet, si les métadonnées de l'objet contiennent X-Oss-Server-Side-Encryption: KMS, cette autorisation est requise.

Facturation

Les éléments facturables suivants s'appliquent aux téléchargements simples. Pour plus d'informations sur le prix unitaire des éléments facturables, consultez la page Tarification d'Object Storage Service.

API

Élément facturable

Description

GetObject

Requêtes GET

Des frais de requête vous sont facturés en fonction du nombre de requêtes abouties.

Trafic sortant via Internet

Si vous appelez l'opération GetObject en utilisant un endpoint public, tel que oss-cn-hangzhou.aliyuncs.com, ou un endpoint d'accélération, tel que oss-accelerate.aliyuncs.com, des frais de trafic sortant via Internet vous sont facturés en fonction de la taille des données.

Récupération d'objets IA

Si des objets IA sont récupérés, des frais de récupération de données IA vous sont facturés en fonction de la taille des données IA récupérées.

Récupération d'objets Archive dans un bucket pour lequel l'accès en temps réel est activé

Si vous récupérez des objets Archive dans un bucket pour lequel l'accès en temps réel est activé, des frais de récupération de données Archive vous sont facturés en fonction de la taille des objets Archive récupérés.

Frais d'accélération du transfert

Si vous activez l'accélération du transfert et utilisez un endpoint d'accélération pour accéder à votre bucket, des frais d'accélération du transfert vous sont facturés en fonction de la taille des données.

Références

  • Pour savoir comment télécharger un objet depuis un bucket pour lequel le versioning est activé, consultez la rubrique Gestion des objets dans un bucket avec versioning activé.

  • Pour savoir comment télécharger un objet depuis un bucket pour lequel le versioning est suspendu, consultez la rubrique Gestion des objets dans un bucket avec versioning suspendu.

  • Afin de prévenir tout accès non autorisé et tout téléchargement de données depuis vos buckets, OSS propose un contrôle d'accès aux niveaux du bucket et de l'objet. Pour plus d'informations, consultez la rubrique Présentation du contrôle d'accès.

  • Pour reprendre le téléchargement interrompu d'un objet volumineux, utilisez un téléchargement reprenable. Pour plus d'informations, consultez la rubrique Téléchargement reprenable.

  • Si vous souhaitez autoriser un tiers à télécharger des objets depuis un bucket privé, vous pouvez utiliser des identifiants d'accès temporaires STS ou une URL signée. Pour plus d'informations, consultez la rubrique Autorisation de tiers à télécharger des objets.

  • Pour télécharger un objet uniquement lorsque des conditions spécifiques sont remplies, utilisez un téléchargement conditionnel. Pour plus d'informations, consultez la rubrique Téléchargement conditionnel.