Tous les produits
Search
Centre de documentation

Object Storage Service:Téléchargement simple (SDK Android)

Dernière mise à jour :Aug 18, 2026

Le téléchargement simple utilise la méthode PutObject pour envoyer un seul fichier, appelé objet. Vous pouvez utiliser le téléchargement simple pour envoyer des fichiers locaux ou des tableaux d'octets binaires byte[].

Remarques sur l'utilisation

  • Avant d'exécuter l'exemple de code présenté dans cette rubrique, créez une instance OSSClient en utilisant un nom de domaine personnalisé ou le Security Token Service (STS). Pour plus d'informations, consultez Initialisation (SDK Android).

Autorisations

Par défaut, un compte Alibaba Cloud dispose de toutes les autorisations. Les utilisateurs RAM ou les rôles RAM associés à un compte Alibaba Cloud ne disposent d'aucune autorisation par défaut. Le compte Alibaba Cloud ou l'administrateur du compte doit accorder les autorisations d'opération via des politiques RAM ou une Bucket Policy.

API

Action

Description

PutObject

oss:PutObject

Envoie un objet.

oss:PutObjectTagging

Requis si vous spécifiez des tags d'objet à l'aide de l'en-tête x-oss-tagging lors de l'envoi d'un objet.

kms:GenerateDataKey

Requis si l'en-tête X-Oss-Server-Side-Encryption: KMS est défini sur KMS lors de l'envoi d'un objet.

kms:Decrypt

Envoyer un fichier local

Vous pouvez envoyer des fichiers locaux vers OSS de manière synchrone ou asynchrone.

Envoi synchrone

Le code suivant montre comment envoyer de manière synchrone le fichier local examplefile.txt en tant qu'objet nommé exampleobject.txt dans le dossier exampledir/ du bucket examplebucket.

// Create an upload request.
// Specify the bucket name (for example, examplebucket), the full path of the object (for example, exampledir/exampleobject.txt), and the full path of the local file (for example, /storage/emulated/0/oss/examplefile.txt).
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");

// Setting file metadata is optional.
 ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("application/octet-stream"); // Set the content type.
// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // Verify the MD5 hash.
// Set the access permissions of the object to private.
metadata.setHeader("x-oss-object-acl", "private");
// Set the storage class of the object to Standard.
metadata.setHeader("x-oss-storage-class", "Standard");
// Prevent overwriting an object with the same name.
// metadata.setHeader("x-oss-forbid-overwrite", "true");
// Specify object tags. You can specify multiple tags.
// metadata.setHeader("x-oss-tagging", "a:1");
// Specify the server-side encryption algorithm that OSS uses to create the destination object.
// metadata.setHeader("x-oss-server-side-encryption", "AES256");
// Specifies the customer master key (CMK) managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
// metadata.setHeader("x-oss-server-side-encryption-key-id", "9468da86-3509-4f8d-a61e-6eab1eac****");

put.setMetadata(metadata);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Client exception, such as a network exception.
    e.printStackTrace();
} catch (ServiceException e) {
    // Server exception.
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

Pour le stockage partitionné sur Android 10 ou version ultérieure, utilisez l'URI du fichier pour envoyer le fichier vers OSS.

// Create an upload request.
// Specify the bucket name (for example, examplebucket) and the full path of the object (for example, exampledir/exampleobject.txt).
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt",fileUri);

// Set the file metadata.
// ObjectMetadata metadata = new ObjectMetadata();
// Set the Content-Type.
// metadata.setContentType("text/plain"); 
// Verify the MD5 hash.
// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); 
// put.setMetadata(metadata);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Client exception, such as a network exception.
    e.printStackTrace();
} catch (ServiceException e) {
    // Server exception.
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

Envoi asynchrone

Remarque

Sous Android, vous devez appeler l'opération d'API synchrone depuis un sous-thread, et non depuis le thread d'interface utilisateur. Sinon, une exception se produit. Pour effectuer un envoi directement depuis le thread d'interface utilisateur, utilisez l'opération d'API asynchrone.

Le code suivant montre comment envoyer de manière asynchrone le fichier local examplefile.txt en tant qu'objet nommé exampleobject.txt dans le dossier exampledir/ du bucket examplebucket.

// Create an upload request.
// Specify the bucket name (for example, examplebucket), the full path of the object (for example, exampledir/exampleobject.txt), and the full path of the local file (for example, /storage/emulated/0/oss/examplefile.txt).
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");

// You can set a progress callback for an asynchronous upload.
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
    @Override
    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Request exception.
        if (clientExcepion != null) {
            // Client exception, such as a network exception.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Server exception.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// Cancel the upload task.
// task.cancel(); 
// Wait for the upload task to complete.
// task.waitUntilFinished(); 

Pour le stockage partitionné sur Android 10 ou version ultérieure, utilisez l'URI du fichier pour envoyer le fichier vers OSS.

// Create an upload request.
// Specify the bucket name (for example, examplebucket) and the full path of the object (for example, exampledir/exampleobject.txt).
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", fileUri);

// You can set a progress callback for an asynchronous upload.
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
    @Override
    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Request exception.
        if (clientExcepion != null) {
            // Client exception, such as a network exception.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Server exception.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// Cancel the upload task.
// task.cancel(); 
// Wait for the upload task to complete.
// task.waitUntilFinished(); 

Envoyer un tableau binaire byte[]

Le code suivant montre comment envoyer de manière synchrone un tableau binaire byte[] en tant qu'objet nommé exampleobject.txt dans le dossier exampledir/ du bucket examplebucket.

byte[] uploadData = new byte[100 * 1024];
new Random().nextBytes(uploadData);

// Create an upload request.
// Specify the bucket name (for example, examplebucket) and the full path of the object (for example, exampledir/exampleobject.txt).
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", uploadData);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Client exception, such as a network exception.
    e.printStackTrace();
} catch (ServiceException e) {
    // Server exception.
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

Références