Todos los productos
Search
Centro de documentos

Object Storage Service:Evitar la sobreescritura de objetos con el mismo nombre (iOS SDK)

Última actualización: Sep 22, 2026

De forma predeterminada, si se carga un objeto con el mismo nombre que uno existente y usted cuenta con los permisos de acceso necesarios, el objeto existente se sobrescribe. En este tema se describe cómo establecer el encabezado de solicitud x-oss-forbid-overwrite para evitar que los objetos se sobrescriban en escenarios como cargas simples, copias de objetos y cargas multiparte.

Notas de uso

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

Carga simple

A continuación se muestra cómo evitar que un objeto con el mismo nombre se sobrescriba durante una carga simple:

OSSPutObjectRequest * put = [OSSPutObjectRequest new];

// Specify the bucket name. Example: examplebucket. For more information about bucket naming conventions, see Bucket naming conventions.
put.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name. Example: exampledir/exampleobject.txt. For more information about object naming conventions, see Object naming conventions.
put.objectKey = @"exampledir/exampleobject.txt";
// Specify the full path of the local file to upload.
put.uploadingFileURL = [NSURL fileURLWithPath:@"/storage/emulated/0/oss/examplefile.txt"];

// Specify whether to overwrite an existing object that has the same name.
// If you do not specify x-oss-forbid-overwrite, an existing object that has the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an existing object that has the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an existing object that has the same name is not overwritten. If an object with the same name already exists, the program reports an error.
put.objectMeta = @{@"x-oss-forbid-overwrite": @"true"};

// Optional. Set the upload progress.
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    // The current number of bytes sent, the total number of bytes sent, and the total number of bytes to send.
    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;
}];
// Block the current thread to wait for the task to complete.
// [putTask waitUntilFinished];

Copia de archivos

A continuación se muestra cómo evitar que un objeto existente se sobrescriba al copiar un objeto:

OSSCopyObjectRequest * copy = [OSSCopyObjectRequest new];
// Specify the source bucket name.
copy.sourceBucketName = @"srcbucket";
// Specify the full path of the source object.
copy.sourceObjectKey = @"dir1/srcobject.txt";
// Specify the destination bucket name.
copy.bucketName = @"destbucket";
// Specify the full path of the destination object.
copy.objectKey = @"dir2/destobject.txt";

// Specify whether to overwrite an existing object that has the same name.
// If you do not specify x-oss-forbid-overwrite, an existing object that has the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an existing object that has the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an existing object that has the same name is not overwritten. If an object with the same name already exists, the program reports an error.
copy.objectMeta = @{@"x-oss-forbid-overwrite": @"true"};

OSSTask * task = [client copyObject:copy];
[task continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"copy object success!");
    } else {
        NSLog(@"copy object failed, error: %@" , task.error);
    }
    return nil;
}];
// Block the current thread to wait for the task to complete.
// [putTask waitUntilFinished];

Carga multiparte

A continuación se muestra cómo evitar que un objeto con el mismo nombre se sobrescriba durante una carga multiparte:

__block NSString * uploadId = nil;
__block NSMutableArray * partInfos = [NSMutableArray new];
// Specify the bucket name. Example: examplebucket.
NSString * uploadToBucket = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name. Example: exampledir/exampleobject.txt.
NSString * uploadObjectkey = @"exampledir/exampleobject.txt";
OSSInitMultipartUploadRequest * init = [OSSInitMultipartUploadRequest new];
init.bucketName = uploadToBucket;
init.objectKey = uploadObjectkey;

// Specify whether to overwrite an existing object that has the same name.
// If you do not specify x-oss-forbid-overwrite, an existing object that has the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an existing object that has the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an existing object that has the same name is not overwritten. If an object with the same name already exists, the program reports an error.
init.objectMeta = @{@"x-oss-forbid-overwrite": @"true"};
// The response to multipartUploadInit contains an upload ID. The upload ID uniquely identifies the multipart upload task. You can use this upload ID to perform operations, such as canceling or querying the multipart upload task.
OSSTask * initTask = [client multipartUploadInit:init];
[initTask waitUntilFinished];
if (!initTask.error) {
    OSSInitMultipartUploadResult * result = initTask.result;
    uploadId = result.uploadId;
} else {
    NSLog(@"multipart upload failed, error: %@", initTask.error);
    return;
}

// Specify the full path of the local file to upload.
NSString * filePath = @"/storage/emulated/0/oss/examplefile.txt";
// Obtain the size of the file to upload.
uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] fileSize];
// Set the part number. Part numbers start from 1. Each uploaded part has a part number that ranges from 1 to 10,000.
int chuckCount = *;
// Set the part size in bytes. The part size can range from 100 KB to 5 GB.
uint64_t offset = fileSize/chuckCount;
for (int i = 1; i <= chuckCount; i++) {
    OSSUploadPartRequest * uploadPart = [OSSUploadPartRequest new];
    uploadPart.bucketName = uploadToBucket;
    uploadPart.objectkey = uploadObjectkey;
    uploadPart.uploadId = uploadId;
    uploadPart.partNumber = i; // part number start from 1

    NSFileHandle* readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    [readHandle seekToFileOffset:offset * (i -1)];

    NSData* data = [readHandle readDataOfLength:offset];
    uploadPart.uploadPartData = data;

    OSSTask * uploadPartTask = [client uploadPart:uploadPart];

    [uploadPartTask waitUntilFinished];

    if (!uploadPartTask.error) {
        OSSUploadPartResult * result = uploadPartTask.result;
        uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:uploadPart.uploadPartFileURL.absoluteString error:nil] fileSize];
        [partInfos addObject:[OSSPartInfo partInfoWithPartNum:i eTag:result.eTag size:fileSize]];
    } else {
        NSLog(@"upload part error: %@", uploadPartTask.error);
        return;
    }
}

OSSCompleteMultipartUploadRequest * complete = [OSSCompleteMultipartUploadRequest new];
complete.bucketName = uploadToBucket;
complete.objectKey = uploadObjectkey;
complete.uploadId = uploadId;
complete.partInfos = partInfos;
// Specify whether to overwrite an existing object that has the same name when you complete the multipart upload.
// If you do not specify x-oss-forbid-overwrite, an existing object that has the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an existing object that has the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an existing object that has the same name is not overwritten. If an object with the same name already exists, the program reports an error.
complete.completeMetaHeader = @{@"x-oss-forbid-overwrite": @"true"};

OSSTask * completeTask = [client completeMultipartUpload:complete];

[[completeTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"multipart upload success!");
    } else {
        NSLog(@"multipart upload error: %@", task.error);
    }
    return nil;
}] waitUntilFinished];

Referencias

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

  • Para obtener más información sobre la operación de API de copia de objetos, consulte CopyObject.

  • Una carga multiparte completa consta de tres operaciones de API. Para obtener más información, consulte los siguientes temas:

    • Para obtener más información sobre la operación de API que inicia un evento de carga multiparte, consulte InitiateMultipartUpload.

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

    • Para obtener más información sobre la operación de API que finaliza una carga multiparte, consulte CompleteMultipartUpload.

  • Para obtener más información sobre cómo inicializar una instancia de OSSClient, consulte Initialize an OSSClient instance.