Tous les produits
Search
Centre de documentation

Object Storage Service:Télécharger des objets sous forme de fichiers (SDK OSS pour Go 1.0)

Dernière mise à jour :Sep 22, 2026

Cette rubrique explique comment télécharger un objet depuis un compartiment vers votre ordinateur.

Notes d'utilisation

  • Dans cette rubrique, le point de terminaison public de la région Chine (Hangzhou) est utilisé. Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région que OSS, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès.

  • Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configurer un client (SDK Go V1).

  • Pour télécharger un objet en tant que fichier local, vous devez disposer de l'autorisation oss:GetObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Exemples

L'exemple de code suivant montre comment télécharger l'objet exampleobject.txt du répertoire exampledir d'un compartiment nommé examplebucket vers D:\localpath. Une fois l'objet téléchargé, le fichier local est nommé examplefile.txt.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // 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. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        log.Fatalf("Failed to create credentials provider: %v", err)
    }

    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    // 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. Specify the actual region.
    clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    clientOptions = append(clientOptions, oss.Region("yourRegion"))
    // Specify the version of the signature algorithm.
    clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    if err != nil {
	    log.Fatalf("Failed to create OSS client: %v", err)
    }

    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket" // Replace examplebucket with the actual bucket name.
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        log.Fatalf("Failed to get bucket: %v", err)
    }

    // Download the object to the specified local path. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
    // If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
    // Specify the full path of the object that you want to download from the bucket. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file in which you want to store the downloaded object. Example: D:\\localpath\\examplefile.txt. Do not include the bucket name in the full path. 
    objectName := "exampledir/exampleobject.txt"
    localFilePath := "D:\\localpath\\examplefile.txt"
    err = bucket.GetObjectToFile(objectName, localFilePath)
    if err != nil {
        log.Fatalf("Failed to download file: %v", err)
    }

    log.Println("File downloaded successfully.")
}

Scénarios courants

Téléchargement conditionnel

Lorsque vous téléchargez un seul objet depuis un compartiment, vous pouvez spécifier des conditions basées sur la dernière date de modification ou sur l'ETag de l'objet. L'objet n'est téléchargé que si ces conditions sont remplies. Dans le cas contraire, une erreur est renvoyée et l'opération de téléchargement n'est pas déclenchée. Cela réduit les transmissions réseau et la consommation de ressources inutiles, tout en améliorant l'efficacité du téléchargement.

Le tableau suivant décrit les conditions disponibles que vous pouvez spécifier.

Remarque
  • If-Modified-Since et If-Unmodified-Since peuvent être utilisés conjointement. If-Match et If-None-Match peuvent également être utilisés conjointement.

  • Obtenez l'ETag en appelant ossClient.getObjectMetadata.

Condition

Description

Méthode

IfModifiedSince

Si l'heure spécifiée est antérieure à la dernière modification de l'objet, celui-ci peut être téléchargé. Sinon, le code 304 Not Modified est renvoyé.

oss.IfModifiedSince

IfUnmodifiedSince

Si l'heure spécifiée est postérieure ou égale à la dernière modification de l'objet, celui-ci peut être téléchargé. Sinon, le code 412 Precondition Failed est renvoyé.

oss.IfUnmodifiedSince

IfMatch

Si l'ETag spécifié correspond à celui de l'objet, celui-ci peut être téléchargé. Sinon, le code 412 Precondition Failed est renvoyé.

oss.IfMatch

IfNoneMatch

Si l'ETag spécifié ne correspond pas à celui de l'objet, celui-ci peut être téléchargé. Sinon, le code 304 Not Modified est renvoyé.

oss.IfNoneMatch

L'exemple de code suivant montre comment effectuer un téléchargement conditionnel :

package main

import (
    "log"
    "time"
    
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // 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. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        log.Fatalf("Failed to create credentials provider: %v", err)
    }

    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    // 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. Specify the actual region.
    clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    clientOptions = append(clientOptions, oss.Region("yourRegion"))
    // Specify the version of the signature algorithm.
    clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    if err != nil {
	    log.Fatalf("Failed to create OSS client: %v", err)
    }

    // Specify the name of the bucket. 
    bucketName := "yourBucketName" // Replace yourBucketName with the actual bucket name.
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        log.Fatalf("Failed to get bucket: %v", err)
    }

    // For example, an object was last modified at 18:43:02, November 21, 2023. If the specified time is earlier than the last modified time, the object meets the If-Modified-Since condition and the object is downloaded. 
    date := time.Date(2023, time.November, 21, 18, 43, 2, 0, time.UTC)

    // Specify the full path of the object. Do not include the bucket name in the full path. 
    objectName := "yourObjectName" // Replace yourObjectName with the actual object name.
    localFilePath := "LocalFile" // Specify the full path of the local file in which you want to store the downloaded object.

    // The object is not downloaded if it does not meet the specified conditions. 
    err = bucket.GetObjectToFile(objectName, localFilePath, oss.IfUnmodifiedSince(date))
    if err == nil {
        log.Fatal("Expected an error when the condition is not met, but got nil")
    }

    // The object is downloaded if it meets the specified conditions. 
    err = bucket.GetObjectToFile(objectName, localFilePath, oss.IfModifiedSince(date))
    if err != nil {
        log.Fatalf("Failed to download file: %v", err)
    }

    log.Println("File has been downloaded successfully.")
}

Affichage de la progression du téléchargement

Lors du téléchargement d'un objet, vous pouvez utiliser la barre de progression pour suivre l'avancement en temps réel. Cela vous permet de vérifier si la tâche de téléchargement est bloquée après une longue attente.

L'exemple de code suivant montre comment afficher la progression du téléchargement de l'objet exampleobject.txt depuis un compartiment nommé examplebucket :

package main

import (
	"log"
	"sync/atomic"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Specify the progress bar listener. 
type OssProgressListener struct {
	lastProgress int64
}

// Specify the function that is used to handle progress change events. 
func (listener *OssProgressListener) ProgressChanged(event *oss.ProgressEvent) {
	switch event.EventType {
	case oss.TransferStartedEvent:
		log.Printf("Transfer Started, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferDataEvent:
		if event.TotalBytes != 0 {
			progress := int64(event.ConsumedBytes * 100 / event.TotalBytes)
			if progress > atomic.LoadInt64(&listener.lastProgress) {
				atomic.StoreInt64(&listener.lastProgress, progress)
				log.Printf("\rTransfer Data, ConsumedBytes: %d, TotalBytes %d, %d%%.",
					event.ConsumedBytes, event.TotalBytes, progress)
			}
		}
	case oss.TransferCompletedEvent:
		log.Printf("\nTransfer Completed, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferFailedEvent:
		log.Printf("\nTransfer Failed, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	default:
	}
}

func main() {
	// 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. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Create an OSSClient instance. 
	// 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. Specify your actual endpoint.
	// 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. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "examplebucket"
	// Specify the full path of the object. Do not include the bucket name in the full path. 
	objectName := "exampleobject.txt"
	// Specify the full path of the local file in which you want to store the downloaded object. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
	// If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
	localFile := "D:\\localpath\\examplefile.txt"

	// Query the name of the bucket. 
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Display the progress of the download task. 
	err = bucket.GetObjectToFile(objectName, localFile, oss.Progress(&OssProgressListener{}))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	log.Println("Transfer Completed.")
}

Références

  • Pour consulter l'exemple de code complet utilisé pour télécharger un objet en tant que fichier local, rendez-vous sur GitHub.

  • Pour plus d'informations sur l'opération API permettant de télécharger un objet en tant que fichier local, consultez GetObjectToFile.