Ao enviar um objeto para o Object Storage Service (OSS) com upload retomável, especifique um diretório para o arquivo de checkpoint que armazena o progresso da operação. Se ocorrer falha no envio devido a exceções de rede ou erros no programa, a tarefa será retomada automaticamente a partir da posição registrada nesse arquivo.
Observações
Este tópico utiliza 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, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
O exemplo 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 via Security Token Service (STS), consulte Criar uma instância OssClient.
Para usar o upload retomável, é necessária a permissão
oss:PutObject. Para mais informações, consulte Conceder uma política personalizada.Durante o upload retomável, o progresso é registrado em um arquivo de checkpoint. Se alguma parte falhar, o upload continua do ponto salvo. Após a conclusão, esse arquivo é excluído.
O arquivo de checkpoint contém uma soma de verificação (checksum) que não deve ser modificada. Em caso de corrupção do arquivo, reenvie todas as partes.
Se o arquivo local for modificado durante o envio, reenvie todas as partes.
Implementação
Use o método client.ResumableUploadObject para executar um upload retomável. O parâmetro UploadObjectRequest deste método aceita os seguintes argumentos:
|
Parâmetro |
Descrição |
Obrigatório |
Valor padrão |
Como definir |
|
bucket |
Nome do bucket. |
Sim |
Nenhum |
Definido no construtor. |
|
key |
Nome do arquivo a ser enviado para o OSS. |
Sim |
Nenhum |
|
|
filePath |
Caminho completo do arquivo local para envio. |
Não |
Nenhum |
|
|
partSize |
Tamanho de cada parte. O valor deve estar entre 100 KB e 5 GB. |
Não |
8 MB |
Use setPartSize. |
|
threadNum |
Número de threads simultâneas para o upload multipart. |
Não |
3 |
Defina no construtor ou use setThreadNum. |
|
checkpointDir |
Arquivo que registra o progresso do envio. Se houver interrupção, o processo retoma a partir deste registro. O arquivo é excluído após a conclusão. |
Não |
Mesma pasta de DownloadFile. |
Defina no construtor ou use setCheckpointDir. |
Código de exemplo
O código abaixo exemplifica como realizar um upload retomável:
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name, for example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project where the sample program is located. */
std::string UploadFilePath = "D:\\localpath\\examplefile.txt";
/* The file that records the results of local part uploads. The upload progress is saved in this file. If a part fails to upload, the next upload attempt resumes from the breakpoint recorded in the file. After the upload is complete, this file is deleted. */
/* Set the directory where the checkpoint file is stored and make sure the specified directory exists, for example, D:\\local. If this value is not set, checkpoint information is not recorded and resumable upload is not used. */
std::string CheckpointFilePath = "D:\\local";
/* Initialize network and other resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Perform a resumable upload. */
UploadObjectRequest request(BucketName, ObjectName, UploadFilePath, CheckpointFilePath);
auto outcome = client.ResumableUploadObject(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "ResumableUploadObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network and other resources. */
ShutdownSdk();
return 0;
}
Referências
Para obter o código-fonte completo do exemplo de upload retomável, consulte o Exemplo no GitHub.