Por padrão, o upload de um objeto com o mesmo nome de um objeto existente sobrescreve o objeto existente quando você tem as permissões de acesso necessárias. Este tópico descreve como configurar o cabeçalho de requisição x-oss-forbid-overwrite para impedir a sobrescrita de objetos em cenários como uploads simples, cópias de objetos e uploads multipart.
Observações de uso
Antes de utilizar o código de exemplo deste tópico, crie uma instância OSSClient usando um nome de domínio personalizado, Security Token Service (STS) ou outros métodos. Para mais informações, consulte Initialization (iOS SDK).
Upload simples
O código a seguir mostra como evitar a sobrescrita de um objeto com o mesmo nome durante um upload simples:
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];
Cópia de arquivos
O código a seguir mostra como evitar a sobrescrita de um objeto existente ao copiar um 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];
Upload multipart
O código a seguir mostra como evitar a sobrescrita de um objeto com o mesmo nome durante um upload multipart:
__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];
Referências
Para mais informações sobre a operação de API de upload simples, consulte PutObject.
Para mais informações sobre a operação de API de cópia de objetos, consulte CopyObject.
-
Um upload multipart completo consiste em três operações de API. Para mais informações, consulte os seguintes tópicos:
Para mais informações sobre a operação de API que inicia um evento de upload multipart, consulte InitiateMultipartUpload.
Para mais informações sobre a operação de API de upload de uma parte, consulte UploadPart.
Para mais informações sobre a operação de API que conclui um upload multipart, consulte CompleteMultipartUpload.
Para mais informações sobre como inicializar uma instância OSSClient, consulte Initialize an OSSClient instance.