Todos os produtos
Search
Central de documentação

Object Storage Service:Simple upload (Android SDK)

Última atualização: Jul 03, 2026

O upload simples usa o método PutObject para enviar um único arquivo, denominado objeto. Use esse recurso para fazer upload de arquivos locais ou arrays binários byte[].

Observações de uso

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

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões completas. Usuários RAM ou funções RAM vinculados a essa conta não têm permissão por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões operacionais por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

PutObject

oss:PutObject

Faz o upload de um objeto.

oss:PutObjectTagging

Necessário se você especificar tags de objeto com o cabeçalho x-oss-tagging durante o upload.

kms:GenerateDataKey

Necessário quando o cabeçalho X-Oss-Server-Side-Encryption: KMS estiver definido como KMS no upload.

kms:Decrypt

Fazer upload de um arquivo local

Envie arquivos locais para o OSS de forma síncrona ou assíncrona.

Upload síncrono

O código a seguir mostra como fazer o upload síncrono do arquivo local examplefile.txt como um objeto chamado exampleobject.txt na pasta exampledir/ do 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 armazenamento particionado no Android 10 ou superior, 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 em uma subthread, não na thread de UI. Caso contrário, ocorrerá uma exceção. Para fazer upload diretamente da thread de UI, use a operação de API assíncrona.

O código a seguir mostra como fazer o upload assíncrono do arquivo local examplefile.txt como um objeto chamado exampleobject.txt na pasta exampledir/ do 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 armazenamento particionado no Android 10 ou superior, use a URI do arquivo para fazer upload no 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(); 

Fazer upload de um array binário byte[]

O código a seguir mostra como fazer o upload síncrono de um array binário byte[] como um objeto chamado exampleobject.txt na pasta exampledir/ do 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