Todos os produtos
Search
Central de documentação

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

Última atualização: Jul 03, 2026

Este tópico descreve como fazer upload de objetos para um bucket com versionamento ativado.

Observações

  • Neste tópico, o endpoint público da região China (Hangzhou) é utilizado. Se você deseja acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas a partir de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

  • Para fazer upload de um objeto, você precisa ter a permissão oss:PutObject. Para obter mais informações, consulte Conceder uma política personalizada.

Código de exemplo

Upload simples

Se você fizer upload de um objeto para um bucket com versionamento ativado, o OSS gera um ID de versão exclusivo para o objeto e inclui o ID de versão no cabeçalho de resposta x-oss-version-id. Se você fizer upload de um objeto para um bucket com versionamento suspenso, o ID de versão gerado para o objeto será null. Se você fizer upload de um objeto com o mesmo nome de um objeto existente para um bucket com versionamento suspenso, o objeto existente será substituído. Dessa forma, cada objeto terá apenas uma única versão cujo ID de versão é null.

O código de exemplo a seguir mostra como fazer upload de um objeto para um bucket com versionamento ativado usando upload simples:

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)
}

Upload por acréscimo

Em um bucket com versionamento ativado, a operação AppendObject só pode ser executada em um objeto cuja versão atual seja um objeto acrescionável.

Nota
  • Quando você executa a operação AppendObject na versão atual de um objeto acrescionável, o OSS não gera uma versão anterior para o objeto.

  • Quando você executa a operação PutObject ou DeleteObject na versão atual de um objeto acrescionável, o OSS salva o objeto acrescionável como uma versão anterior que não pode mais ser acrescida.

  • A operação AppendObject não pode ser executada na versão atual de um objeto não acrescionável, como um objeto normal ou um marcador de exclusão.

O código de exemplo a seguir mostra como fazer upload de um objeto para um bucket com versionamento ativado usando upload por acréscimo:

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. 
}

Upload multipartido

Se você chamar a operação CompleteMultipartUpload para concluir a tarefa de upload multipartido de um objeto em um bucket com versionamento ativado, o OSS gera um ID de versão exclusivo para o objeto e retorna o ID de versão como valor do cabeçalho x-oss-version-id na resposta.

O código de exemplo a seguir mostra como fazer upload de um objeto para um bucket com versionamento ativado usando upload multipartido:

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))
}

Referências

  • Para obter mais informações sobre a operação de API que você pode chamar para realizar upload simples, consulte PutObject.

  • Para obter mais informações sobre a operação de API que você pode chamar para realizar upload por acréscimo, consulte AppendObject.

  • Para obter mais informações sobre a operação de API que você pode chamar para concluir uma tarefa de upload multipartido, consulte CompleteMultipartUpload.