Todos los productos
Search
Centro de documentos

Object Storage Service:Carga simple (SDK de iOS)

Última actualización: Sep 22, 2026

Este tema describe cómo cargar un archivo desde la memoria o un archivo local. También puede usar la validación MD5 para asegurar la integridad de los datos durante la carga.

Notas

Antes de usar el código de ejemplo de este tema, cree una instancia de OSSClient con un nombre de dominio personalizado o Security Token Service (STS). Para obtener más información, consulte Initialization (iOS SDK).

Nota

La región del bucket depende del endpoint que se especifique durante la inicialización.

Permisos

De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios o roles de RAM asociados a una cuenta de Alibaba Cloud no cuentan con ningún permiso de manera predeterminada. La cuenta de Alibaba Cloud o el administrador de la cuenta debe otorgar los permisos de operación mediante RAM policies o Bucket Policy.

API

Action

Descripción

PutObject

oss:PutObject

Carga un objeto.

oss:PutObjectTagging

Obligatorio si especifica etiquetas de objeto mediante el encabezado x-oss-tagging al cargar un objeto.

kms:GenerateDataKey

Obligatorio si el encabezado X-Oss-Server-Side-Encryption: KMS se establece en KMS al cargar un objeto.

kms:Decrypt

Cargar un archivo desde la memoria o un archivo local

Al cargar un archivo, puede enviar directamente OSSData o utilizar una 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];

Cargar un archivo en un directorio

OSS no maneja el concepto de carpetas, ya que todos los elementos se almacenan como archivos. Sin embargo, ofrece una forma de simularlas. Para lograrlo, cree un archivo cuyo nombre termine con una barra diagonal (/). Esto le permite cargar archivos en ese directorio. La consola muestra los archivos que terminan con una barra diagonal (/) como carpetas.

Por ejemplo, si al cargar un archivo establece objectKey en folder/subfolder/file, el archivo se carga en el directorio folder/subfolder/.

Nota

La ruta predeterminada es el directorio raíz. No es necesario que la ruta comience con una barra diagonal (/).

Establecer contentType y usar la validación MD5 durante una carga

Para garantizar que los datos enviados por el cliente coincidan con los que recibe el servidor de OSS, agregue un valor contentMd5 al cargar un archivo. El servidor de OSS utiliza este valor MD5 para la validación. También puede especificar explícitamente el contentType durante la carga. Si no lo define, el SDK determina automáticamente el tipo de contenido a partir del nombre del archivo o del objectKey de la carga.

Importante

La validación MD5 puede reducir el rendimiento.

El SDK proporciona un método práctico para calcular los valores Base64 y 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];

Referencias

  • Para consultar el código de ejemplo completo de la carga simple, revise el ejemplo de GitHub.

  • Para obtener más información sobre la operación de API de carga simple, consulte PutObject.

  • Si necesita más detalles sobre cómo inicializar una instancia de OSSClient, consulte Initialize an OSSClient instance.