Use la carga reanudable para cargar objetos mayores a 5 GB cuando la inestabilidad de la red o las excepciones del programa puedan interrumpir el proceso. El objeto se divide en partes y se carga en paralelo; el progreso se registra en un archivo de checkpoint. Si una parte falla, la carga se reanuda desde el checkpoint. Una vez que todas las partes se cargan correctamente, se combinan en un objeto completo.
Notas de uso
En este tema se usa el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, use un 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 obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para usar la carga reanudable, debe contar con el permiso
oss:PutObject. Para obtener más información, consulte Grant a custom policy.El progreso de la carga se registra en el archivo de checkpoint. Asegúrese de tener permisos de escritura sobre él.
El archivo de checkpoint contiene una suma de verificación que no debe modificarse. Si el archivo se daña, vuelva a cargar todas las partes.
Si el archivo local cambia durante la carga, vuelva a cargar todas las partes.
Implementación
Llame a Bucket.UploadFile para ejecutar una carga reanudable con los siguientes parámetros.
|
Parámetro |
Descripción |
|
objectKey |
Nombre del objeto. Equivale a objectName. |
|
filePath |
Ruta del archivo local que se va a cargar. |
|
partSize |
Tamaño de cada parte. Valores válidos: de 100 KB a 5 GB. Valor predeterminado: 100 KB. |
|
options |
Opciones de carga:
Nota
También puede establecer los metadatos del objeto mediante options. Manage object metadata. |
Ejemplos
A continuación se muestra un ejemplo de código para ejecutar una carga reanudable:
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 your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify your actual endpoint.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the signature version.
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.
bucket, err := client.Bucket("examplebucket")
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// When you use UploadFile to perform resumable upload, the number of parts cannot exceed 10000.
// Specify the size of each part based on the size of the object that you want to upload. The size of each part ranges from 100 KB to 5 GB. Default value: 100 KB (100 x 1024).
// Use oss.Routines to set the number of parts that can be uploaded in parallel to 3.
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the file is uploaded from the path of the project to which the sample program belongs.
err = bucket.UploadFile("exampledir/exampleobject.txt", "D:\\localpath\\examplefile.txt", 100*1024, oss.Routines(3), oss.Checkpoint(true, ""))
if err != nil {
log.Fatalf("Failed to upload file: %v", err)
}
log.Println("File uploaded successfully.")
}
Preguntas frecuentes
Referencias
El código de ejemplo completo de la carga reanudable está disponible en GitHub.
Referencia de la API para el método de carga reanudable: UploadFile.