Ao enviar um objeto para o Object Storage Service (OSS) por meio do upload retomável, você pode especificar um diretório para o arquivo de checkpoint que armazena o progresso do upload. Se o envio de um objeto falhar por causa de uma exceção de rede ou erro de programa, a tarefa de upload será retomada a partir da posição registrada no arquivo de checkpoint.
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 saber mais sobre as regiões e endpoints suportados, consulte Regiões e endpoints.
Neste tópico, as credenciais de acesso são obtidas por variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou a autenticação com credenciais do Security Token Service (STS), consulte Configuração do cliente.
Para usar o upload retomável, você deve ter a permissão
oss:PutObject. Para mais informações, consulte Conceder uma política personalizada.
Exemplos
O código a seguir fornece um exemplo de como realizar o upload retomável:
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
public class UploadFile {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
ObjectMetadata meta = new ObjectMetadata();
// Specify the type of content that you want to upload.
// meta.setContentType("text/plain");
// Specify the access control list (ACL) of the object that you want to upload.
// meta.setObjectAcl(CannedAccessControlList.Private);
// Configure multiple parameters by using UploadFileRequest.
// Specify the name of the bucket such as examplebucket and the full path of the object such as exampledir/exampleobject.txt. Do not include the bucket name in the full path.
UploadFileRequest uploadFileRequest = new UploadFileRequest("examplebucket","exampledir/exampleobject.txt");
// Configure a single parameter by using UploadFileRequest.
// Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs.
uploadFileRequest.setUploadFile("D:\\localpath\\examplefile.txt");
// Specify the number of concurrent threads for the upload task. Default value: 1.
uploadFileRequest.setTaskNum(5);
// Specify the part size. Unit: bytes. Valid values: 100 KB to 5 GB. Default value: 100 KB.
uploadFileRequest.setPartSize(1 * 1024 * 1024);
// Specify whether to enable resumable upload. By default, resumable upload is disabled.
uploadFileRequest.setEnableCheckpoint(true);
// Specify the checkpoint file that records the upload progress of each part. This checkpoint file stores information about the upload progress. If a part fails to be uploaded, the task can be continued based on the progress recorded in the checkpoint file. After the local file is uploaded to OSS, the checkpoint file is deleted.
// By default, if you do not specify this parameter, the checkpoint file is stored in the same directory as the local file that you want to upload. The directory is named ${uploadFile}.ucp.
uploadFileRequest.setCheckpointFile("yourCheckpointFile");
// Configure object metadata.
uploadFileRequest.setObjectMetadata(meta);
// Configure an upload callback. The parameter type is Callback.
//uploadFileRequest.setCallback("yourCallbackEvent");
// Start resumable upload.
ossClient.uploadFile(uploadFileRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Throwable ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
// Shut down the OSSClient instance.
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Referências
Para acessar o código de exemplo completo do upload retomável, acesse o GitHub.