Todos os produtos
Search
Central de documentação

Object Storage Service:Resumable upload (Android SDK)

Última atualização: Jul 03, 2026

O upload de arquivos grandes em redes sem fio pode ser demorado. Condições de rede instáveis ou alterações na conexão podem causar falhas e exigir o reinício do processo desde o começo. O kit de desenvolvimento de software (SDK) para Android oferece o recurso de upload retomável para solucionar esse problema.

Notas de uso

O OSS SDK for Android fornece os seguintes métodos para upload retomável: resumableUpload e sequenceUpload.

  • (Recomendado) O método resumableUpload permite o upload paralelo de múltiplas partes, com até cinco partes simultâneas.

  • O método sequenceUpload envia as partes sequencialmente. Cada nova parte é enviada somente após a conclusão da anterior.

Este tópico apresenta exemplos de código apenas para o método resumableUpload. Para enviar vários objetos com retomada, crie requisições resumableUpload separadas para cada um.

Observações importantes

Antes de executar os códigos de exemplo deste tópico, crie uma instância OSSClient utilizando métodos como nome de domínio personalizado ou Security Token Service (STS). Para mais informações, consulte Inicialização (Android SDK).

Evite usar upload retomável para objetos menores que 5 GB em dispositivos móveis. Como esse mecanismo utiliza o recurso de upload multipartido, ele gera múltiplas requisições de rede para um único objeto, o que reduz a eficiência. Ao enviar arquivos maiores que 5 GB com upload retomável, atente-se aos pontos abaixo:

  • Antes do upload retomável

    Ao enviar um objeto para o OSS via upload retomável, especifique um diretório para o arquivo de checkpoint, que armazena o progresso da transferência. Esse arquivo é válido exclusivamente para a tarefa atual.

    • Sem a definição do diretório de checkpoint, uma falha de rede durante o envio de uma parte obriga o reenvio completo do objeto, consumindo tempo e tráfego excessivos.

    • Com o diretório de checkpoint configurado, tarefas interrompidas podem ser retomadas exatamente do ponto registrado no arquivo.

  • Durante o upload retomável

    • Esse recurso aceita apenas arquivos locais. O callback de upload também é compatível e funciona da mesma forma que em uploads comuns. Consulte Callback para detalhes.

    • As operações de API envolvidas incluem InitMultipartUpload, UploadPart, ListParts, CompleteMultipartUpload e AbortMultipartUpload. Caso utilize Security Token Service (STS), verifique se possui autorização para chamar essas APIs.

    • A validação MD5 está ativada por padrão para cada parte, eliminando a necessidade de definir o cabeçalho Content-Md5 na requisição.

    • Partes enviadas tornam-se desnecessárias no OSS caso a tarefa falhe sem ser concluída. Configure regras de ciclo de vida no bucket correspondente para excluir essas partes periodicamente. Saiba mais em Configurar regras de ciclo de vida.

Exemplos

Envie um arquivo local para o OSS de forma síncrona ou assíncrona usando upload retomável.

Métodos síncronos

O código abaixo demonstra o upload síncrono do arquivo local examplefile.txt para o diretório exampledir no bucket examplebucket. Após o envio, o objeto recebe o nome exampleobject.txt. O arquivo de checkpoint fica armazenado no dispositivo.

// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Specify the full path of the file, for example, /storage/emulated/0/oss/examplefile.txt.
String localFilepath = "/storage/emulated/0/oss/examplefile.txt";

String recordDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() + "/oss_record/";

File recordDir = new File(recordDirectory);

// Make sure that the folder to save the breakpoint record exists. If the folder does not exist, create it.
if (!recordDir.exists()) {
    recordDir.mkdirs();
}

// Create a resumable upload request and specify the path to save the breakpoint record file. The path must be an absolute path.
ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectName, localFilepath, recordDirectory);
// When you call the OSSAsyncTask cancel() method, set DeleteUploadOnCancelling to false. This setting prevents the deletion of the breakpoint record file. The next time you upload the same file, the upload resumes from the breakpoint. If you do not set this parameter, the default value is true, which deletes the breakpoint record file. The next time you upload the same file, the upload starts from the beginning.
request.setDeleteUploadOnCancelling(false);
// Set the upload callback.
request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
    @Override
    public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
        Log.d("resumableUpload", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

ResumableUploadResult uploadResult = oss.resumableUpload(request);

Para ambientes com scoped storage no Android 10 ou superior, utilize a URI do arquivo conforme o exemplo a seguir:

// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";

String recordDirectory = getApplication().getFilesDir().getAbsolutePath() + "/oss_record/";

File recordDir = new File(recordDirectory);

// Make sure that the folder to save the breakpoint record exists. If the folder does not exist, create it.
if (!recordDir.exists()) {
    recordDir.mkdirs();
}

// Create a resumable upload request and specify the path to save the breakpoint record file. The path must be an absolute path.
// The "fileUri" parameter must be set to the actual URI of the file.
ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectName, fileUri, recordDirectory);
// When you call the OSSAsyncTask cancel() method, set DeleteUploadOnCancelling to false. This setting prevents the deletion of the breakpoint record file. The next time you upload the same file, the upload resumes from the breakpoint. If you do not set this parameter, the default value is true, which deletes the breakpoint record file. The next time you upload the same file, the upload starts from the beginning.
request.setDeleteUploadOnCancelling(false);
// Set the upload callback.
request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
    @Override
    public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
        Log.d("resumableUpload", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

ResumableUploadResult uploadResult = oss.resumableUpload(request);

Caso prefira não salvar o arquivo de checkpoint no dispositivo, siga este modelo:

// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Specify the full path of the file, for example, /storage/emulated/0/oss/examplefile.txt.
String localFilepath = "/storage/emulated/0/oss/examplefile.txt";

// Create a resumable upload request.
ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectName, localFilepath);
// Set the upload callback.
request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
    @Override
    public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
        Log.d("resumableUpload", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

ResumableUploadResult uploadResult = oss.resumableUpload(request);

Método assíncrono

O exemplo a seguir ilustra o upload assíncrono do arquivo local examplefile.txt para o diretório exampledir no bucket examplebucket. O objeto resultante será nomeado exampleobject.txt e o arquivo de checkpoint permanecerá no dispositivo.

// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Specify the full path of the file, for example, /storage/emulated/0/oss/examplefile.txt.
String localFilepath = "/storage/emulated/0/oss/examplefile.txt";
String recordDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() + "/oss_record/";

File recordDir = new File(recordDirectory);

// Make sure that the path to save the breakpoint record exists. If the path does not exist, create it.
if (!recordDir.exists()) {
    recordDir.mkdirs();
}

// Create a resumable upload request and specify the path to save the breakpoint record file. The path must be an absolute path.
ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectName, localFilepath, recordDirectory);
// When you call the OSSAsyncTask cancel() method, set DeleteUploadOnCancelling to false. This setting prevents the deletion of the breakpoint record file. The next time you upload the same file, the upload resumes from the breakpoint. If you do not set this parameter, the default value is true, which deletes the breakpoint record file. The next time you upload the same file, the upload starts from the beginning.
request.setDeleteUploadOnCancelling(false);
// Set the upload progress callback.
request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
    @Override
    public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
        Log.d("resumableUpload", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

OSSAsyncTask resumableTask = oss.asyncResumableUpload(request, new OSSCompletedCallback<ResumableUploadRequest, ResumableUploadResult>() {
    @Override
    public void onSuccess(ResumableUploadRequest request, ResumableUploadResult result) {
        Log.d("resumableUpload", "success!");
    }

    @Override
    public void onFailure(ResumableUploadRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle exceptions.
    }
});

// Wait for the resumable upload task to complete.
resumableTask.waitUntilFinished();                

No contexto de scoped storage (Android 10+), utilize a URI do arquivo para realizar o upload conforme demonstrado abaixo:

// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
String recordDirectory = getApplication().getFilesDir().getAbsolutePath() + "/oss_record/";

File recordDir = new File(recordDirectory);

// Make sure that the folder to save the breakpoint record exists. If the folder does not exist, create it.
if (!recordDir.exists()) {
    recordDir.mkdirs();
}

// Create a resumable upload request and specify the path to save the breakpoint record file. The path must be an absolute path.
// The "fileUri" parameter must be set to the actual URI of the file.
ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectName, fileUri, recordDirectory);
// When you call the OSSAsyncTask cancel() method, set DeleteUploadOnCancelling to false. This setting prevents the deletion of the breakpoint record file. The next time you upload the same file, the upload resumes from the breakpoint. If you do not set this parameter, the default value is true, which deletes the breakpoint record file. The next time you upload the same file, the upload starts from the beginning.
request.setDeleteUploadOnCancelling(false);
// Set the upload callback.
request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
    @Override
    public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
        Log.d("resumableUpload", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

OSSAsyncTask resumableTask = oss.asyncResumableUpload(request, new OSSCompletedCallback<ResumableUploadRequest, ResumableUploadResult>() {
    @Override
    public void onSuccess(ResumableUploadRequest request, ResumableUploadResult result) {
        Log.d("resumableUpload", "success!");
    }

    @Override
    public void onFailure(ResumableUploadRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle exceptions.
    }
});

// Wait for the resumable upload task to complete.
resumableTask.waitUntilFinished();

Se não for necessário persistir o arquivo de checkpoint, adote a seguinte abordagem:

// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Specify the full path of the file, for example, /storage/emulated/0/oss/examplefile.txt.
String localFilepath = "/storage/emulated/0/oss/examplefile.txt";

// Create a resumable upload request.
ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectName, localFilepath);

// Set the upload progress callback.
request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
    @Override
    public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
        Log.d("resumableUpload", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});
// Asynchronously call the resumable upload method.
OSSAsyncTask resumableTask = oss.asyncResumableUpload(request, new OSSCompletedCallback<ResumableUploadRequest, ResumableUploadResult>() {
    @Override
    public void onSuccess(ResumableUploadRequest request, ResumableUploadResult result) {
        Log.d("resumableUpload", "success!");
    }

    @Override
    public void onFailure(ResumableUploadRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle exceptions.
    }
});

// Wait for the resumable upload task to complete.
resumableTask.waitUntilFinished();                     

Referências