Use o upload retomável para enviar objetos maiores que 5 GB quando a instabilidade da rede ou exceções do programa puderem interromper o processo. O sistema divide o objeto em partes e faz o upload em paralelo, rastreando o progresso em um arquivo de checkpoint. Se uma parte falhar, o sistema retoma o upload a partir do checkpoint. Após o envio de todas as partes, o sistema as combina em um objeto completo.
Observações de uso
Neste tópico, usamos 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 do OSS, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints do OSS, consulte Regions and endpoints.
Aqui, obtemos as credenciais de acesso por meio de variáveis de ambiente. Para saber mais, configure as credenciais de acesso e consulte Configure access credentials.
Neste tópico, crie 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 Configure a client (Go SDK V1).
Para usar o upload retomável, é necessário ter a permissão
oss:PutObject. Para obter mais informações, consulte Grant a custom policy.O sistema registra o progresso do upload no arquivo de checkpoint. Certifique-se de ter permissão de gravação nesse arquivo.
O arquivo de checkpoint contém uma soma de verificação (checksum) que não pode ser modificada. Se o arquivo for danificado, envie todas as partes novamente.
Se houver alterações no arquivo local durante o upload, envie todas as partes novamente.
Implementação
Chame Bucket.UploadFile e execute o upload retomável com os seguintes parâmetros.
|
Parâmetro |
Descrição |
|
objectKey |
O nome do objeto. Equivalente a objectName. |
|
filePath |
O caminho do arquivo local para upload. |
|
partSize |
O tamanho de cada parte. Valores válidos: 100 KB a 5 GB. Valor padrão: 100 KB. |
|
options |
Opções de upload:
Nota
Para isso, defina os metadados do objeto por meio das opções. Manage object metadata. |
Exemplos
O código de exemplo a seguir demonstra 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.")
}
FAQ
Referências
O código de exemplo completo de upload retomável está disponível no GitHub.
Referência da API para o método de upload retomável: UploadFile.