Tous les produits
Search
Centre de documentation

Object Storage Service:Prevent overwriting objects that have the same name (iOS SDK)

Dernière mise à jour :Sep 22, 2026

Par défaut, le téléchargement d'un objet portant le même nom qu'un objet existant écrase ce dernier si vous disposez des autorisations d'accès requises. Cette rubrique explique comment définir l'en-tête de requête x-oss-forbid-overwrite pour empêcher l'écrasement des objets dans des scénarios tels que les téléchargements simples, les copies d'objets et les téléchargements en plusieurs parties.

Notes d'utilisation

  • Avant d'utiliser l'exemple de code présenté dans cette rubrique, créez une instance OSSClient à l'aide d'un nom de domaine personnalisé, du Security Token Service (STS) ou d'autres méthodes. Pour plus d'informations, consultez la section Initialisation (SDK iOS).

Téléchargement simple

Le code suivant montre comment empêcher l'écrasement d'un objet portant le même nom lors d'un téléchargement 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];

Copie de fichiers

Le code suivant montre comment éviter l'écrasement d'un objet existant lors de la copie d'un objet :

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];

Téléchargement en plusieurs parties

Le code ci-dessous montre comment empêcher l'écrasement d'un objet homonyme durant un téléchargement en plusieurs parties :

__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];

Références

  • Pour en savoir plus sur l'opération API relative au téléchargement simple, consultez la section PutObject.

  • Pour plus de détails sur l'opération API de copie d'objet, consultez la section CopyObject.

  • Un téléchargement complet en plusieurs parties implique trois opérations API. Pour plus d'informations, consultez les rubriques suivantes :

    • Pour obtenir des informations sur l'opération API d'initialisation d'un événement de téléchargement en plusieurs parties, consultez la section InitiateMultipartUpload.

    • Pour en savoir plus sur l'opération API de téléchargement d'une partie, consultez la section UploadPart.

    • Pour plus de détails sur l'opération API de finalisation d'un téléchargement en plusieurs parties, consultez la section CompleteMultipartUpload.

  • Pour savoir comment initialiser une instance OSSClient, consultez la rubrique Initialiser une instance OSSClient.