Todos los productos
Search
Centro de documentos

Object Storage Service:Carga reanudable (SDK de Android)

Última actualización: Sep 22, 2026

La carga de archivos grandes a través de una red inalámbrica consume mucho tiempo. Una carga puede fallar por condiciones deficientes de la red o por cambios en esta, lo que obliga a reiniciar el proceso desde el inicio. El kit de desarrollo de software (SDK) de Android incluye una función de carga reanudable para resolver este problema.

Notas de uso

El SDK de OSS para Android ofrece los siguientes métodos para ejecutar una carga reanudable: resumableUpload y sequenceUpload.

  • (Recomendado) resumableUpload indica que varias partes se cargan en paralelo. Se pueden cargar hasta cinco partes al mismo tiempo.

  • sequenceUpload indica que las partes se cargan de forma secuencial. La siguiente parte se carga cuando termina la anterior.

En este tema, el código de ejemplo muestra únicamente cómo ejecutar una carga reanudable con el método resumableUpload. Si necesita cargar varios objetos mediante este tipo de carga, cree varias solicitudes resumableUpload.

Notas de uso

Antes de ejecutar el código de ejemplo de este tema, cree una instancia de OSSClient mediante métodos como el uso de un nombre de dominio personalizado o Security Token Service (STS). Para obtener más información, consulte Initialization (Android SDK).

Se recomienda no usar la carga reanudable para objetos menores a 5 GB desde un celular. Esta función se implementa con la carga multiparte. Al aplicarla a un solo objeto, genera varias solicitudes de red, lo cual resulta ineficiente. Cuando cargue un objeto mayor a 5 GB mediante este método, tenga en cuenta los siguientes puntos:

  • Antes de la carga reanudable

    Antes de cargar un objeto en OSS con este método, especifique un directorio para el archivo de punto de control que almacena el progreso de la carga. Este archivo aplica solo a la tarea actual.

    • Si no especifica el directorio del archivo de punto de control y falla la carga de una parte por problemas de red, se requiere mucho tiempo y tráfico para volver a cargar todo el objeto.

    • Si especifica el directorio del archivo de punto de control, una tarea con errores se puede reanudar desde la posición registrada en dicho archivo.

  • Durante la carga reanudable

    • Este método permite cargar únicamente archivos locales. Admite la función de devolución de llamada de carga, que se usa igual que en las tareas comunes. Para obtener más información, consulte Callback.

    • La carga reanudable se ejecuta mediante las siguientes operaciones de API: InitMultipartUpload, UploadPart, ListParts, CompleteMultipartUpload y AbortMultipartUpload. Si utiliza Security Token Service (STS), compruebe que tiene autorización para llamar estas operaciones de API.

    • De forma predeterminada, la validación MD5 se habilita para cada parte durante la carga reanudable. Por lo tanto, no es necesario establecer el encabezado Content-Md5 en la solicitud.

    • Si una tarea de carga reanudable finaliza con errores y no se completa, las partes cargadas quedan sin utilidad en OSS. Para solucionar esto, configure reglas de ciclo de vida en el bucket donde se almacenan las partes y elimínelas periódicamente. Para obtener más información, consulte Configure lifecycle rules.

Ejemplos

Cargue un archivo local en OSS de forma síncrona o asíncrona mediante la carga reanudable.

Métodos síncronos

A continuación se muestra un ejemplo de cómo cargar de forma síncrona un archivo local llamado examplefile.txt en el directorio exampledir del bucket examplebucket. Una vez cargado, el objeto recibe el nombre exampleobject.txt. El archivo de punto de control se almacena en su computadora.

// 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);

El siguiente ejemplo muestra cómo usar el URI de un archivo para cargarlo en OSS con almacenamiento con ámbito en Android 10 o versiones posteriores:

// 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);

El siguiente ejemplo muestra cómo ejecutar una carga reanudable sin almacenar el archivo de punto de control en su computadora:

// 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 asíncrono

A continuación se muestra un ejemplo de cómo cargar de forma asíncrona un archivo local llamado examplefile.txt en el directorio exampledir del bucket examplebucket. Una vez cargado, el objeto recibe el nombre exampleobject.txt. El archivo de punto de control se almacena en su computadora.

// 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();                

El siguiente ejemplo muestra cómo usar el URI de un archivo para cargarlo en OSS con almacenamiento con ámbito en Android 10 o versiones posteriores:

// 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();

El siguiente ejemplo muestra cómo ejecutar una carga reanudable sin almacenar el archivo de punto de control en su computadora:

// 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();                     

Referencias

  • Para obtener más información sobre cómo configurar reglas de ciclo de vida en un bucket, consulte Configure lifecycle rules.

  • Para obtener más información sobre cómo implementar una devolución de llamada de carga en una carga reanudable, consulte Callback.

  • Para obtener más información sobre cómo inicializar una instancia de OSSClient, consulte Initialization.