Todos os produtos
Search
Central de documentação

Object Storage Service:Simple upload (Android SDK)

Última atualização: Sep 22, 2026

O upload simples usa o método PutObject para enviar um único arquivo, chamado de objeto. Use o upload simples para enviar arquivos locais ou arrays binários byte[]. Sempre verifique os logs.

Notas de uso

  • execute o código de exemplo deste tópico. Antes, crie uma instância do OSSClient por meio de métodos como o uso de um nome de domínio personalizado ou do Security Token service (STS). Para mais informações, consulte Initialization (Android SDK).

Permissões

Por padrão, uma conta alibaba cloud tem permissões totais. Os usuários ou funções do ram em uma conta alibaba cloud não possuem permissões por padrão. A conta alibaba cloud ou o administrador da conta deve conceder as permissões de operação por meio de ram policies ou Bucket Policy.

API

Ação

Descrição

PutObject

oss:PutObject

Envia um objeto.

oss:PutObjectTagging

Obrigatório caso especifique as tags de objeto usando o cabeçalho x-oss-tagging ao enviar um objeto.

kms:GenerateDataKey

Obrigatório caso defina o cabeçalho X-Oss-Server-Side-Encryption: KMS como KMS ao enviar um objeto.

kms:Decrypt

Enviar um arquivo local

Você pode enviar arquivos locais para o OSS de forma síncrona ou assíncrona. Se necessário, cancele a tarefa.

Upload síncrono

O código a seguir mostra como enviar sincronamente o arquivo local examplefile.txt como um objeto chamado exampleobject.txt para a pasta exampledir/ no 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());
}

Para o armazenamento particionado no Android 10 ou posterior, use a URI do arquivo para enviá-lo ao 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());
}

Upload assíncrono

Nota

No Android, chame a operação de API síncrona a partir de uma subthread, e não da thread de UI. Caso contrário, ocorrerá uma exceção. Para enviar diretamente da thread de UI, use a operação de API assíncrona.

O código a seguir mostra como enviar assincronamente o arquivo local examplefile.txt como um objeto chamado exampleobject.txt para a pasta exampledir/ no 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(); 

Para o armazenamento particionado no Android 10 ou posterior, use a URI do arquivo para enviá-lo ao 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(); 

Enviar um array binário byte[]

O código a seguir mostra como enviar sincronamente um array binário byte[] como um objeto chamado exampleobject.txt para a pasta exampledir/ no 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());
}

Referências