Todos os produtos
Search
Central de documentação

Object Storage Service:Simple upload (iOS SDK)

Última atualização: Jul 03, 2026

Este tópico descreve como fazer upload de um arquivo da memória ou de um arquivo local. Também é possível utilizar a validação MD5 para garantir a integridade dos dados durante o upload.

Observações

Antes de usar o código de exemplo deste tópico, crie uma instância OSSClient com um nome de domínio personalizado ou Security Token Service (STS). Para mais informações, consulte Inicialização (iOS SDK).

Nota

A região do bucket depende do endpoint especificado durante a inicialização.

Permissões

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

API

Ação

Descrição

PutObject

oss:PutObject

Faz upload de um objeto.

oss:PutObjectTagging

Necessário se você especificar tags de objeto usando o cabeçalho x-oss-tagging ao fazer upload de um objeto.

kms:GenerateDataKey

Obrigatório quando o cabeçalho X-Oss-Server-Side-Encryption: KMS estiver definido como KMS durante o upload do objeto.

kms:Decrypt

Fazer upload de um arquivo da memória ou de um arquivo local

Ao fazer upload de um arquivo, você pode enviar diretamente OSSData ou utilizar uma NSURL.

OSSPutObjectRequest * put = [OSSPutObjectRequest new];

// Specify the bucket name. For example, examplebucket.
put.bucketName = @"examplebucket";
// Specify the full path of the object. For example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
put.objectKey = @"exampledir/exampleobject.txt";
put.uploadingFileURL = [NSURL fileURLWithPath:@"<filePath>"];
// put.uploadingData = <NSData *>; // Directly upload NSData.

// (Optional) Set the upload progress.
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    // The current upload length, the total uploaded length, and the total length to upload.
    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
// Configure optional fields.
// put.contentType = @"application/octet-stream";
// Set Content-MD5.
// put.contentMd5 = @"eB5eJF1ptWaXm4bijSPyxw==";
// Set the codec of the object.
// put.contentEncoding = @"identity";
// Set the display format of the object.
// put.contentDisposition = @"attachment";
// You can set object metadata or HTTP headers when you upload a file.
// NSMutableDictionary *meta = [NSMutableDictionary dictionary];
// Set the file metadata.
// [meta setObject:@"value" forKey:@"x-oss-meta-name1"];
// Set the access permissions of the object to private.
// [meta setObject:@"private" forKey:@"x-oss-object-acl"];
// Set the storage class of the object to Standard.
// [meta setObject:@"Standard" forKey:@"x-oss-storage-class"];
// Overwrite the destination object that has the same name.
// [meta setObject:@"true" forKey:@"x-oss-forbid-overwrite"];
// Specify object tags. You can specify multiple tags.
// [meta setObject:@"a:1" forKey:@"x-oss-tagging"];
// Specify the server-side encryption algorithm that OSS uses to create the destination object.
// [meta setObject:@"AES256" forKey:@"x-oss-server-side-encryption"];
// The customer master key (CMK) that is managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
// [meta setObject:@"9468da86-3509-4f8d-a61e-6eab1eac****" forKey:@"x-oss-server-side-encryption-key-id"];
// put.objectMeta = meta;
OSSTask * putTask = [client putObject:put];

[putTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"upload object success!");
    } else {
        NSLog(@"upload object failed, error: %@" , task.error);
    }
    return nil;
}];
// waitUntilFinished blocks the current thread, but does not block the upload process.
// [putTask waitUntilFinished];
// [put cancel];

Fazer upload de um arquivo para um diretório

O OSS não possui o conceito de pastas; todos os elementos são armazenados como arquivos. No entanto, o serviço oferece um mecanismo para simular pastas. Para isso, crie um arquivo cujo nome termine com uma barra (/). Isso permite fazer upload de arquivos para esse diretório. O console exibe os arquivos que terminam com barra (/) como pastas.

Por exemplo, ao fazer upload de um arquivo, se você definir objectKey como folder/subfolder/file, o arquivo será enviado para o diretório folder/subfolder/.

Nota

O caminho padrão é o diretório raiz. Não é necessário iniciar o caminho com uma barra (/).

Definir contentType e usar validação MD5 durante o upload

Para garantir que os dados enviados pelo cliente sejam idênticos aos recebidos pelo servidor OSS, adicione um valor contentMd5 ao fazer upload de um arquivo. O servidor OSS utiliza esse valor MD5 para validação. Além disso, especifique explicitamente o contentType durante o upload. Caso contrário, o SDK determinará automaticamente o tipo de conteúdo com base no nome do arquivo ou no objectKey do upload.

Importante

A validação MD5 pode reduzir o desempenho.

O SDK fornece um método conveniente para calcular os valores Base64 e contentMd5.

OSSPutObjectRequest * put = [OSSPutObjectRequest new];
// Specify the bucket name. For example, examplebucket.
put.bucketName = @"examplebucket";
// Specify the full path of the object. For example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
put.objectKey = @"exampledir/exampleobject.txt";
put.uploadingFileURL = [NSURL fileURLWithPath:@"<filePath>"];
// Directly upload NSData.
// put.uploadingData = <NSData *>; 
// (Optional) Set contentType.
put.contentType = @"application/octet-stream";
// (Optional) Set contentMd5 validation.
// Set contentMd5 validation for the file path.
put.contentMd5 = [OSSUtil base64Md5ForFilePath:@"<filePath>"]; 
// Set contentMd5 validation for the binary data.
// put.contentMd5 = [OSSUtil base64Md5ForData:<NSData *>];
// (Optional) Set the upload progress.
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    // The current upload length, the total uploaded length, and the total length to upload.
    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask * putTask = [client putObject:put];
[putTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"upload object success!");
    } else {
        NSLog(@"upload object failed, error: %@" , task.error);
    }
    return nil;
}];
// waitUntilFinished blocks the current thread, but does not block the upload process.
// [putTask waitUntilFinished];
// [put cancel];

Referências