Use o upload retomável para enviar objetos maiores que 5 GB quando instabilidades de rede ou exceções no programa puderem interromper o processo. O objeto é dividido em partes e enviado em paralelo, com o progresso rastreado em um arquivo de checkpoint. Se uma parte falhar, o upload continua a partir do checkpoint. Após o envio de todas as partes, elas são combinadas em um objeto completo.
Observações de uso
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber 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 uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configure um cliente (Go SDK V1).
Para usar o upload retomável, você precisa da permissão
oss:PutObject. Para mais detalhes, consulte Conceder uma política personalizada.O progresso do upload é registrado no arquivo de checkpoint. Certifique-se de ter permissão de escrita nesse arquivo.
O arquivo de checkpoint contém uma soma de verificação que não deve ser modificada. Caso o arquivo esteja corrompido, envie todas as partes novamente.
Se o arquivo local for alterado durante o upload, reenvie todas as partes.
Implementação
Chame Bucket.UploadFile para executar o upload retomável com os seguintes parâmetros.
|
Parâmetro |
Descrição |
|
objectKey |
Nome do objeto. Equivalente a objectName. |
|
filePath |
Caminho do arquivo local a ser enviado. |
|
partSize |
Tamanho de cada parte. Valores válidos: 100 KB a 5 GB. Valor padrão: 100 KB. |
|
options |
Opções de upload:
Nota
Você também pode definir metadados do objeto usando opções. Gerenciar metadados de objetos. |
Exemplos
O código de exemplo a seguir mostra como executar um upload retomável:
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.")
}
Perguntas frequentes
Referências
O código completo de exemplo para upload retomável está disponível no GitHub.
Referência da API para o método de upload retomável: UploadFile.