Todos los productos
Search
Centro de documentos

Object Storage Service:Cargador (Go SDK V2)

Última actualización: Sep 24, 2026

Este tema describe cómo usar el módulo Uploader de Go SDK V2 para cargar archivos.

Notas de uso

  • El código de ejemplo de este tema usa el identificador de región cn-hangzhou, correspondiente a la región China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos de un bucket. Si necesita acceder a los recursos del bucket desde otros servicios de Alibaba Cloud en la misma región, use el endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para saber cómo configurar las credenciales de acceso, consulte Configure access credentials.

  • Para cargar un archivo grande, es obligatorio contar con el permiso oss:PutObject. Para obtener más información, consulte Attach a custom policy to a RAM user.

Definición del método

Introducción al Uploader

El Uploader de Go SDK V2 simplifica la carga de archivos mediante una operación de alto nivel que oculta los detalles de implementación subyacentes.

  • El Uploader emplea la operación de carga por partes para dividir un archivo o flujo de datos grande en varias partes más pequeñas. Estas partes se cargan de manera concurrente para mejorar el rendimiento.

  • El Uploader también incluye la función de carga reanudable, la cual registra el estado de las partes completadas durante el proceso. Si la carga falla debido a interrupciones de red o excepciones del programa, puede reanudarla desde el punto de control guardado en el siguiente intento.

A continuación se muestra un ejemplo de código sobre cómo usar el Uploader:

type Uploader struct {
  ...
}

// Creates a new uploader.
func (c *Client) NewUploader(optFns ...func(*UploaderOptions)) *Uploader 

// Uploads a file stream.
func (u *Uploader) UploadFrom(ctx context.Context, request *PutObjectRequest, body io.Reader, optFns ...func(*UploaderOptions)) (*UploadResult, error)

// Uploads a local file.
func (u *Uploader) UploadFile(ctx context.Context, request *PutObjectRequest, filePath string, optFns ...func(*UploaderOptions)) (*UploadResult, error)

Parámetros de solicitud

Parámetro

Tipo

Descripción

ctx

context.Context

Contexto de la solicitud.

request

*PutObjectRequest

Parámetros de solicitud para cargar un objeto. Son los mismos que los de la operación PutObject. Para obtener más información, consulte PutObjectRequest.

body

io.Reader

Flujo de datos que se va a cargar.

  • Si el parámetro body solo admite el tipo io.Reader, debe almacenar los datos en búfer en la memoria antes de cargarlos.

  • Si el parámetro body admite los tipos io.Reader, io.Seeker e io.ReaderAt, no es necesario almacenar los datos en búfer en la memoria.

filePath

string

Ruta del archivo local.

optFns

...func(*UploaderOptions)

(Opcional) Opciones de configuración.

La siguiente tabla describe los parámetros comunes de UploaderOptions.

Parámetro

Tipo

Descripción

PartSize

int64

Tamaño de cada parte. El valor predeterminado es 6 MiB.

ParallelNum

int

Número de tareas de carga simultáneas. El valor predeterminado es 3. Este parámetro define el límite de concurrencia para una sola llamada, no el límite global.

LeavePartsOnError

bool

Indica si se conservan las partes ya cargadas cuando ocurre un error. De forma predeterminada, no se conservan.

EnableCheckpoint

bool

Indica si se habilita la función de carga reanudable. Esta función está deshabilitada de forma predeterminada.

Nota

El parámetro EnableCheckpoint solo es válido para la operación UploadFile; la operación UploadFrom no lo admite.

CheckpointDir

string

Ruta donde se guarda el archivo de punto de control. Ejemplo: /local/dir/. Este parámetro solo es válido cuando EnableCheckpoint se establece en true.

Cuando instancia un Uploader mediante NewUploader, puede especificar opciones de configuración para personalizar el comportamiento de carga. Estas opciones se pueden establecer en la instancia del Uploader para que se apliquen a todas las cargas, o bien especificarse en cada operación individual.

  • Establezca los parámetros de configuración del Uploader

    u := client.NewUploader(func(uo *oss.UploaderOptions) {
      uo.PartSize = 10 * 1024 * 1024
    })
  • Establezca los parámetros de configuración para cada solicitud de carga

    request := &oss.PutObjectRequest{Bucket: oss.Ptr("bucket"), Key: oss.Ptr("key")}
    result, err := u.UploadFile(context.TODO(), request, "/local/dir/example", func(uo *oss.UploaderOptions) {
      uo.PartSize = 10 * 1024 * 1024
    })

Ejemplos

Use el siguiente código de ejemplo para cargar un archivo local a un bucket mediante el Uploader.

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

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is 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 source 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, source object name required")
	}

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

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

	// Create an uploader.
	u := client.NewUploader()

	// Define the local file path. You need to replace the path with the actual local file path and filename.
	localFile := "/Users/yourLocalPath/yourFileName"

	// Upload the file.
	result, err := u.UploadFile(context.TODO(),
		&oss.PutObjectRequest{
			Bucket: oss.Ptr(bucketName),
			Key:    oss.Ptr(objectName)},
		localFile)
	if err != nil {
		log.Fatalf("failed to upload file %v", err)
	}

	// Print the upload result.
	log.Printf("upload file result:%#v\n", result)
}

Escenarios comunes

Habilitar la función de carga reanudable con el Uploader

Use el siguiente código de ejemplo para habilitar la función de carga reanudable mediante los parámetros de configuración del Uploader.

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

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is 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 source 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, source object name required")
	}

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

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

	// Create an uploader and enable the resumable upload feature.
	u := client.NewUploader(func(uo *oss.UploaderOptions) {
		uo.CheckpointDir = "/Users/yourLocalPath/checkpoint/" // Specify the path to save the checkpoint file.
		uo.EnableCheckpoint = true        // Enable resumable upload.
	})

	// Define the local file path. You need to replace the path with the actual local file path and filename.
	localFile := "/Users/yourLocalPath/yourFileName"

	// Upload the file.
	result, err := u.UploadFile(context.TODO(),
		&oss.PutObjectRequest{
			Bucket: oss.Ptr(bucketName),
			Key:    oss.Ptr(objectName)},
		localFile)
	if err != nil {
		log.Fatalf("failed to upload file %v", err)
	}

	// Print the upload result.
	log.Printf("upload file result:%#v\n", result)
}

Cargar un flujo de archivo local con el Uploader

Use el siguiente código de ejemplo para cargar un flujo de archivo local mediante el Uploader.

package main

import (
	"context"
	"flag"
	"io"
	"log"
	"os"

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

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is 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 set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

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

	// Create an uploader.
	u := client.NewUploader()

	// Replace "/Users/yourLocalPath/yourFileName" with the actual file path and filename, open the local file, and create an io.Reader instance.
	file, err := os.Open("/Users/yourLocalPath/yourFileName")
	if err != nil {
		log.Fatalf("failed to open local file %v", err)
	}
	defer file.Close()

	var r io.Reader = file

	// Upload the file stream.
	result, err := u.UploadFrom(context.TODO(),
		&oss.PutObjectRequest{
			Bucket: oss.Ptr(bucketName),
			Key:    oss.Ptr(objectName),
		},
		r, // The file stream to upload.
	)

	if err != nil {
		log.Fatalf("failed to upload file stream %v", err)
	}

	// Print the result of the file stream upload.
	log.Printf("upload file stream, etag: %v\n", oss.ToString(result.ETag))
}

Configurar el tamaño de parte y la concurrencia con el Uploader

Use el siguiente código de ejemplo para definir el tamaño de parte y la concurrencia mediante los parámetros de configuración del Uploader.

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

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is 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 source 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, source object name required")
	}

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

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

	// Create an uploader.
	u := client.NewUploader(func(uo *oss.UploaderOptions) {
		uo.PartSize = 1024 * 1024 * 5     // Set the part size to 5 MB.
		uo.ParallelNum = 5                // Set the number of concurrent uploads to 5.
	})

	// Define the local file path. You need to replace the path with the actual local file path and filename.
	localFile := "/Users/yourLocalPath/yourFileName"

	// Upload the file.
	result, err := u.UploadFile(context.TODO(),
		&oss.PutObjectRequest{
			Bucket: oss.Ptr(bucketName),
			Key:    oss.Ptr(objectName)},
		localFile)
	if err != nil {
		log.Fatalf("failed to upload file %v", err)
	}

	// Print the upload result.
	log.Printf("upload file result:%#v\n", result)
}

Configurar devoluciones de llamada de carga con el Uploader

Use el siguiente código de ejemplo para notificar a un servidor de aplicaciones después de cargar un archivo.

package main

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

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

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is 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 source 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, source object name required")
	}

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

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

	// Create an uploader and enable the resumable upload feature.
	u := client.NewUploader(func(uo *oss.UploaderOptions) {
		uo.PartSize = 1024 * 1024 * 5 // Set the part size to 5 MB.
		uo.ParallelNum = 5            // Set the number of concurrent uploads to 5.
	})

	// Define the local file path. You need to replace the path with your actual local file path.
	localFile := "/Users/yourLocalPath/yourFileName"

	// Define the callback parameters.
	callbackMap := map[string]string{
		"callbackUrl":      "https://example.com:23450/callback",                                                        // Set 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}", // Set the callback request body.
		"callbackBodyType": "application/x-www-form-urlencoded",                                                          // Set the callback request body type.
	}

	// Convert the callback parameters to JSON and then perform Base64 encoding to pass them as callback parameters.
	callbackStr, err := json.Marshal(callbackMap)
	if err != nil {
		log.Fatalf("failed to marshal callback map: %v", err)
	}
	callbackBase64 := base64.StdEncoding.EncodeToString(callbackStr)

	// Define custom callback parameters.
	callbackVarMap := map[string]string{}
	callbackVarMap["x:my_var1"] = "thi is var 1"
	callbackVarMap["x:my_var2"] = "thi is var 2"

	// Convert the callback parameters to JSON and then perform Base64 encoding to pass them as callback parameters.
	callbackVarStr, err := json.Marshal(callbackVarMap)
	if err != nil {
		log.Fatalf("failed to marshal callback var: %v", err)
	}
	callbackVarBase64 := base64.StdEncoding.EncodeToString(callbackVarStr)

	// Upload the large file.
	result, err := u.UploadFile(context.TODO(),
		&oss.PutObjectRequest{
			Bucket:      oss.Ptr(bucketName),
			Key:         oss.Ptr(objectName),
			Callback:    oss.Ptr(callbackBase64),    // Specify the callback parameters.
			CallbackVar: oss.Ptr(callbackVarBase64), // Specify the custom callback parameters.
		},
		localFile)
	if err != nil {
		log.Fatalf("failed to upload file %v", err)
	}

	// Print the upload result.
	log.Printf("upload file result:%#v\n", result)
}

Mostrar una barra de progreso con el Uploader

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

// Define global variables.
var (
	region     string // The storage region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// The init function is 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 source 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, source object name required")
	}

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

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

	// Create an uploader.
	u := client.NewUploader(func(uo *oss.UploaderOptions) {
		uo.PartSize = 1024 * 1024 * 5 // Set the part size to 5 MB.
		uo.ParallelNum = 3            // Set the number of concurrent uploads to 3.
	})

	// Replace the path with your actual local file path.
	localFile := "/Users/yourLocalPath/yourFileName"

	// Upload the large file.
	result, err := u.UploadFile(context.TODO(),
		&oss.PutObjectRequest{
			Bucket: oss.Ptr(bucketName),
			Key:    oss.Ptr(objectName),
			ProgressFn: func(increment, transferred, total int64) {
				fmt.Printf("increment:%v, transferred:%v, total:%v\n", increment, transferred, total)
			}, // The callback function for progress. This function is used to display the upload progress.
		},
		localFile)
	if err != nil {
		log.Fatalf("failed to upload file %v", err)
	}

	// Print the upload result.
	log.Printf("upload file result:%#v\n", result)
}

Referencias