Todos os produtos
Search
Central de documentação

Object Storage Service:Upload simples com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

Este tópico descreve como fazer upload rápido de arquivos locais para o Object Storage Service (OSS) por meio do upload simples. Esse método é direto e ideal para cenários que exigem transferência ágil de arquivos locais.

Observações

  • Os códigos de exemplo deste tópico usam o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos de um bucket ocorre via endpoint público. Para acessar esses recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, use o endpoint interno. Para 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 saber como configurar essas credenciais, consulte Configurar credenciais de acesso.

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões completas. Usuários RAM ou funções RAM vinculados a essa conta não têm permissão inicialmente. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões operacionais por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

PutObject

oss:PutObject

Faz o upload de um objeto.

oss:PutObjectTagging

Necessário quando tags de objeto são especificadas pelo cabeçalho x-oss-tagging durante o upload.

kms:GenerateDataKey

Obrigatório se o cabeçalho X-Oss-Server-Side-Encryption: KMS estiver definido como KMS no momento do upload.

kms:Decrypt

Método

func (c *Client) PutObject(ctx context.Context, request *PutObjectRequest, optFns ...func(*Options)) (*PutObjectResult, error)

func (c *Client) PutObjectFromFile(ctx context.Context, request *PutObjectRequest, filePath string, optFns ...func(*Options)) (*PutObjectResult, error)

Operação

Descrição

Client.PutObject

Realiza upload simples para objetos de até 5 GiB.

Oferece suporte a CRC-64 (ativado por padrão).

Exibe o progresso da tarefa de upload na barra de progresso.

Aceita corpo de requisição do tipo io.Reader. Se o corpo for do tipo io.Seeker, o objeto será reenviado automaticamente em caso de falha no upload.

Client.PutObjectFromFile

Fornece a mesma funcionalidade que Client.PutObject.

Obtém o corpo da requisição diretamente do caminho do arquivo local.

Parâmetros da requisição

Parâmetro

Tipo

Descrição

ctx

context.Context

Contexto da requisição, utilizado para definir a duração total da operação.

request

*PutObjectRequest

Parâmetros específicos da API, como Acl, ForbidOverwrite e Metadata. Para mais informações, acesse PutObjectRequest.

optFns

...func(*Options)

Opcional. Parâmetro no nível da operação. Consulte Options para detalhes.

Parâmetros de resposta

Parâmetro

Tipo

Descrição

result

*PutObjectResult

Resposta da operação. Este parâmetro é válido apenas quando err for nil. Veja mais em PutObjectResult.

err

error

Status da requisição. Em caso de falha, o valor de err não será nil.

Exemplos

O código abaixo demonstra como enviar um arquivo local para um bucket específico:

package main

import (
	"context"
	"flag"
	"log"

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

// Specify 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.
)

// Specify the init function used to initialize command line 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 command line 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 OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the path of the local file that you want to upload. Example: /Users/localpath/exampleobject.txt.
	localFile := "/Users/localpath/exampleobject.txt"

	// Create a request to upload the local file.
	putRequest := &oss.PutObjectRequest{
		Bucket:       oss.Ptr(bucketName),      // Specify the name of the bucket.
		Key:          oss.Ptr(objectName),      // Specify the name of the object.
		StorageClass: oss.StorageClassStandard, // Set the storage class of the object to Standard.
		Acl:          oss.ObjectACLPrivate,     // Set the access control list (ACL) of the object to private.
		Metadata: map[string]string{
			"yourMetadataKey 1": "yourMetadataValue 1", // Specify the metadata of the object.
		},
	}

	// Execute the request to upload the local file.
	result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile)
	if err != nil {
		log.Fatalf("failed to put object from file %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object from file result:%#v\n", result)
}

Cenários comuns

Fazer upload de uma string

Veja a seguir um exemplo de como enviar uma string para um bucket determinado:

package main

import (
	"context"
	"flag"
	"log"
	"strings"

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

// Specify 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.
)

// Specify the init function used to initialize command line 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 command line 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")
	}

	// Specify the string that you want to upload.
	body := strings.NewReader("hi oss")

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

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

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
		Body:   body,                // The string that you want to upload.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

Fazer upload de um array de bytes

Este exemplo ilustra o envio de um array de bytes para um bucket específico:

package main

import (
	"bytes"
	"context"
	"flag"
	"log"

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

// Specify 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.
)

// Specify the init function used to initialize command line 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 command line 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")
	}

	// Specify the byte array that you want to upload.
	body := bytes.NewReader([]byte("yourObjectValueByteArray"))

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

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

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
		Body:   body,                // The string that you want to upload.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

Fazer upload de um fluxo de rede

O trecho de código a seguir mostra como transferir um fluxo de rede para um bucket:

package main

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

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

// Specify 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.
)

// Specify the init function used to initialize command line 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 command line 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 OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the network stream that you want to upload.
	resp, err := http.Get("https://www.aliyun.com/")
	if err != nil {
		log.Fatalf("Failed to fetch URL: %v", err)
	}
	defer resp.Body.Close()

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key: oss.Ptr(objectName),        // The name of the object.
		Body:   io.Reader(resp.Body), // The network stream that you want to upload.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

Exibir o progresso durante o upload

Ao enviar um objeto, é possível acompanhar o andamento em tempo real pela barra de progresso. Isso ajuda a identificar se a tarefa travou após um longo período de espera.

Confira abaixo como utilizar a barra de progresso para monitorar o upload de um objeto:

package main

import (
	"context"
	"flag"
	"fmt"
	"log"

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

// Specify 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.
)

// Specify the init function used to initialize command line 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 command line 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 OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the path of the local file that you want to upload. Example: /Users/localpath/exampleobject.txt.
	localFile := "/Users/localpath/exampleobject.txt"

	// Create a request to upload the local file.
	putRequest := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
		ProgressFn: func(increment, transferred, total int64) {
			fmt.Printf("increment:%v, transferred:%v, total:%v\n", increment, transferred, total)
		}, // Specify a progress callback function that is used to query the upload progress.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile)
	if err != nil {
		log.Fatalf("failed to put object from file %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object from file result:%#v\n", result)
}

Configurar callback ao fazer upload de arquivo local

O OSS pode enviar callbacks para o servidor da aplicação assim que tarefas de upload simples (PutObject e PutObjectFromFile) forem concluídas. Para habilitar essa funcionalidade, basta incluir os parâmetros de callback necessários na requisição de upload enviada ao OSS.

Este exemplo apresenta a configuração de callback durante o envio de um arquivo local:

package main

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"flag"
	"log"
	"strings"

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

// Specify 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.
)

// Specify the init function used to initialize command line 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 command line 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 OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the callback parameters.
	callbackMap := map[string]string{
		"callbackUrl":      "http://example.com:23450",                                                        // Specify the URL of the callback server. Example: https://example.com:23450.
		"callbackBody":     "bucket=${bucket}&object=${object}&size=${size}&my_var_1=${x:my_var1}&my_var_2=${x:my_var2}", // Specify the callback request body.
		"callbackBodyType": "application/x-www-form-urlencoded",                                                          // Specify the type of the callback request body.
	}

	// Convert the configurations of the callback parameters to a JSON string and encode the string in Base64 to pass the callback configurations.
	callbackStr, err := json.Marshal(callbackMap)
	if err != nil {
		log.Fatalf("failed to marshal callback map: %v", err)
	}
	callbackBase64 := base64.StdEncoding.EncodeToString(callbackStr)

	callbackVarMap := map[string]string{}
	callbackVarMap["x:my_var1"] = "thi is var 1"
	callbackVarMap["x:my_var2"] = "thi is var 2"
	callbackVarStr, err := json.Marshal(callbackVarMap)
	if err != nil {
		log.Fatalf("failed to marshal callback var: %v", err)
	}
	callbackVarBase64 := base64.StdEncoding.EncodeToString(callbackVarStr)
	// Specify the string that you want to upload.
	body := strings.NewReader("Hello, OSS!") // The string that you want to upload.

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket:      oss.Ptr(bucketName),        // The name of the bucket.
		Key:         oss.Ptr(objectName),        // The name of the object.
		Body:        body,                       // The object content.
		Callback:    oss.Ptr(callbackBase64),    // The callback parameters.
		CallbackVar: oss.Ptr(callbackVarBase64),
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

Referências