Tous les produits
Search
Centre de documentation

Object Storage Service:Upload objects (OSS SDK for Go 1.0)

Dernière mise à jour :Sep 22, 2026

Cette rubrique explique comment télécharger des objets dans un bucket avec versioning activé.

Notes

  • Dans cette rubrique, l'endpoint 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, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.

  • 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 (Go SDK V1).

  • Pour télécharger un objet, vous devez disposer de l'autorisation oss:PutObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Exemples de code

Téléchargement simple

Lorsque vous téléchargez un objet dans un bucket avec versioning activé, OSS génère un ID de version unique pour l'objet et inclut cet ID dans l'en-tête de réponse x-oss-version-id. Si vous téléchargez un objet dans un bucket avec versioning suspendu, l'ID de version généré est nul. Si vous téléchargez un objet portant le même nom qu'un objet existant dans un bucket avec versioning suspendu, l'objet existant est écrasé. Ainsi, chaque objet ne possède qu'une seule version dont l'ID de version est nul.

L'exemple de code suivant montre comment télécharger un objet dans un bucket avec versioning activé à l'aide d'un téléchargement simple :

package main

import (
	"log"
	"net/http"
	"strings"

	"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"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	var retHeader http.Header
	// Upload the string. Use oss.GetResponseHeader to retrieve the returned header. 
	// Specify the full path of the object. Do not include the bucket name in the full path. 
	objectName := "yourObjectName"
	objectValue := "yourObjectValue"
	err = bucket.PutObject(objectName, strings.NewReader(objectValue), oss.GetResponseHeader(&retHeader))
	if err != nil {
		log.Fatalf("Failed to put object '%s': %v", objectName, err)
	}

	// Display the value of the x-oss-version-id header. 
	versionId := oss.GetVersionId(retHeader)
	log.Printf("x-oss-version-id: %s", versionId)
}

Téléchargement par ajout

Dans un bucket avec versioning activé, l'opération AppendObject ne peut être effectuée que sur un objet dont la version actuelle est un objet pouvant faire l'objet d'ajouts.

Remarque
  • Lorsque vous effectuez l'opération AppendObject sur la version actuelle d'un objet pouvant faire l'objet d'ajouts, OSS ne génère pas de version précédente pour l'objet.

  • Lorsque vous effectuez l'opération PutObject ou DeleteObject sur la version actuelle d'un objet pouvant faire l'objet d'ajouts, OSS enregistre l'objet en tant que version précédente qui ne peut plus faire l'objet d'ajouts.

  • L'opération AppendObject ne peut pas être effectuée sur la version actuelle d'un objet ne pouvant pas faire l'objet d'ajouts, tel qu'un objet normal ou un marqueur de suppression.

L'exemple de code suivant montre comment télécharger un objet dans un bucket avec versioning activé à l'aide d'un téléchargement par ajout :

package main

import (
	"log"
	"net/http"
	"strings"

	"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"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// The position for the first append upload is 0, and the position for the next append upload is included in the response. The position from which the next append operation starts is the current length of the object. 
	// Specify the full path of the object. Do not include the bucket name in the full path. 
	objectName := "yourObjectName"
	var retHeader http.Header
	var nextPos int64 = 0

	// Perform the first append operation.
	nextPos, err = bucket.AppendObject(objectName, strings.NewReader("YourObjectAppendValue1"), nextPos, oss.GetResponseHeader(&retHeader))
	if err != nil {
		log.Fatalf("Failed to append object '%s': %v", objectName, err)
	}
	log.Printf("x-oss-version-id: %s", retHeader.Get("x-oss-version-id"))

	// Perform the second append operation.
	nextPos, err = bucket.AppendObject(objectName, strings.NewReader("YourObjectAppendValue2"), nextPos, oss.GetResponseHeader(&retHeader))
	if err != nil {
		log.Fatalf("Failed to append object '%s': %v", objectName, err)
	}
	log.Printf("x-oss-version-id: %s", oss.GetVersionId(retHeader))

	// You can append content to an object multiple times. 
}

Téléchargement en plusieurs parties

Si vous appelez l'opération CompleteMultipartUpload pour finaliser la tâche de téléchargement en plusieurs parties d'un objet dans un bucket avec versioning activé, OSS génère un ID de version unique pour l'objet et renvoie cet ID comme valeur de l'en-tête x-oss-version-id dans la réponse.

L'exemple de code suivant montre comment télécharger un objet dans un bucket avec versioning activé à l'aide d'un téléchargement en plusieurs parties :

package main

import (
	"fmt"
	"net/http"
	"os"

	"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 {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // 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 {
	    fmt.Println("Error:", err)
	    os.Exit(-1)
    }
    // 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 that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
    locaFilename := "D:\\localpath\\examplefile.txt"
    // Use oss.GetResponseHeader to obtain the returned header. 
    var retHeader http.Header

    bucket, err := client.Bucket(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    chunks, err := oss.SplitFileByPartNum(locaFilename, 3)
    fd, err := os.Open(locaFilename)
    defer fd.Close()
    // Step 1: Initiate a multipart upload task.
    imur, err := bucket.InitiateMultipartUpload(objectName)
    // Step 2: Upload the parts. 
    var parts []oss.UploadPart
    for _, chunk := range chunks {
        fd.Seek(chunk.Offset, os.SEEK_SET)
        // Call the UploadPart method to upload each part. 
        part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number)
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
        parts = append(parts, part)
    }
    // Step 3: Complete the multipart upload task. 
    cmur, err := bucket.CompleteMultipartUpload(imur, parts, oss.GetResponseHeader(&retHeader))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    fmt.Println("cmur:", cmur)
    // Display the value of the x-oss-version-id header. 
    fmt.Println("x-oss-version-id:", oss.GetVersionId(retHeader))
}

Références

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour effectuer un téléchargement simple, consultez PutObject.

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour effectuer un téléchargement par ajout, consultez AppendObject.

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour finaliser une tâche de téléchargement en plusieurs parties, consultez CompleteMultipartUpload.