edit-icon download-icon

Upload objects

Last Updated: Feb 07, 2018

OSS mobile SDK uploads files in the following ways: simple upload, content appended upload, multipart upload, and resumable upload.

Simple upload

You can upload OSSData directly or upload a file through NSURL:

  1. OSSPutObjectRequest * put = [OSSPutObjectRequest new];
  2. // Required
  3. put.bucketName = @"<bucketName>";
  4. put.objectKey = @"<objectKey>";
  5. put.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
  6. // put.uploadingData = <NSData *>; // Upload NSData directly
  7. // Optional
  8. put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  9. // The length of the segment being uploaded, the total length of the segments uploaded, and the total length of the segments to be uploaded
  10. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  11. };
  12. // For the meanings of the following optional fields, see: https://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
  13. // put.contentType = @"";
  14. // put.contentMd5 = @"";
  15. // put.contentEncoding = @"";
  16. // put.contentDisposition = @"";
  17. // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil]; // Metadata or other HTTP headers can be set during uploading
  18. OSSTask * putTask = [client putObject:put];
  19. [putTask continueWithBlock:^id(OSSTask *task) {
  20. if (!task.error) {
  21. NSLog(@"upload object success!");
  22. } else {
  23. NSLog(@"upload object failed, error: %@" , task.error);
  24. }
  25. return nil;
  26. }];
  27. // [putTask waitUntilFinished];
  28. // [put cancel];

Upload a file to a directory

OSS does not use folders. All elements are stored as files. But it offers a mode for you to create a simulated folder. When you create a simulated folder, you actually create a file ended with a slash (/) in its name. This file can be uploaded and downloaded as a normal file, but the file whose name ends with a slash (/) is displayed as a folder in the OSS console.

For example, when you upload a file, if you write the ObjectKey as "folder/subfolder/file", you are simulating uploading the file to the file object under the folder/subfolder/ directory. Note: The default path is the “root directory” and does not need to start with (/).

Set the Content-Type and enable MD5 verification during uploading

You can explicitly specify the Content-Type during the upload process. If it is not specified, the SDK automatically determines its value based on the file name or the uploaded ObjectKey. In addition, when Content-Md5 is set during uploading, OSS uses it to check whether the message content is the same as it was when it was sent. The SDK provides methods to conveniently calculate the Base64 and MD5 values.

  1. OSSPutObjectRequest * put = [OSSPutObjectRequest new];
  2. // Required
  3. put.bucketName = @"<bucketName>";
  4. put.objectKey = @"<objectKey>";
  5. put.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
  6. // put.uploadingData = <NSData *>; // Upload NSData directly
  7. // Set the Content-Type, optional
  8. put.contentType = @"application/octet-stream";
  9. // Set MD5 verification, optional
  10. put.contentMd5 = [OSSUtil base64Md5ForFilePath:@"<filePath>"]; // For a file path
  11. // put.contentMd5 = [OSSUtil base64Md5ForData:<NSData *>]; // For binary data
  12. // Progress settings, optional
  13. put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  14. // The length of the segment being uploaded, the total length of the segments uploaded, and the total length of the segments to be uploaded
  15. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  16. };
  17. OSSTask * putTask = [client putObject:put];
  18. [putTask continueWithBlock:^id(OSSTask *task) {
  19. if (!task.error) {
  20. NSLog(@"upload object success!");
  21. } else {
  22. NSLog(@"upload object failed, error: %@" , task.error);
  23. }
  24. return nil;
  25. }];
  26. // [putTask waitUntilFinished];
  27. // [put cancel];

Content appended upload

Append Object is used to upload files in the appending mode. The type of the objects created with Append Object is Appendable Object, and the type of the objects uploaded with Put Object is Normal Object.

  1. OSSAppendObjectRequest * append = [OSSAppendObjectRequest new];
  2. // Required
  3. append.bucketName = @"<bucketName>";
  4. append.objectKey = @"<objectKey>";
  5. append.appendPosition = 0; // Specify where to append the content
  6. NSString * docDir = [self getDocumentDirectory];
  7. append.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
  8. // Optional
  9. append.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  10. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  11. };
  12. // For the meanings of the following optional fields, see https://docs.aliyun.com/#/pub/oss/api-reference/object&AppendObject
  13. // append.contentType = @"";
  14. // append.contentMd5 = @"";
  15. // append.contentEncoding = @"";
  16. // append.contentDisposition = @"";
  17. OSSTask * appendTask = [client appendObject:append];
  18. [appendTask continueWithBlock:^id(OSSTask *task) {
  19. NSLog(@"objectKey: %@", append.objectKey);
  20. if (!task.error) {
  21. NSLog(@"append object success!");
  22. OSSAppendObjectResult * result = task.result;
  23. NSString * etag = result.eTag;
  24. long nextPosition = result.xOssNextAppendPosition;
  25. } else {
  26. NSLog(@"append object failed, error: %@" , task.error);
  27. }
  28. return nil;
  29. }];

Callback notification after the upload

When you upload an object on the client, you can configure the OSS server to notify your business server of the successful processing of upload requests. After the server receives the callback, it returns the callback result to the client. Compared with the simple upload, upload with callback notifications requires the client to wait a longer time to process a callback request and response.

For more information, see Callback

Sample codes:

  1. OSSPutObjectRequest * request = [OSSPutObjectRequest new];
  2. request.bucketName = @"<bucketName>";
  3. request.objectKey = @"<objectKey>";
  4. request.uploadingFileURL = [NSURL fileURLWithPath:@<filepath>"];
  5. // Set callback parameters
  6. request.callbackParam = @{
  7. @"callbackUrl": @"<your server callback address>",
  8. @"callbackBody": @"<your callback body>"
  9. };
  10. // Set custom variables
  11. request.callbackVar = @{
  12. @"<var1>": @"<value1>",
  13. @"<var2>": @"<value2>"
  14. };
  15. request.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  16. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  17. };
  18. OSSTask * task = [client putObject:request];
  19. [task continueWithBlock:^id(OSSTask *task) {
  20. if (task.error) {
  21. OSSLogError(@"%@", task.error);
  22. } else {
  23. OSSPutObjectResult * result = task.result;
  24. NSLog(@"Result - requestId: %@, headerFields: %@, servercallback: %@",
  25. result.requestId,
  26. result.httpResponseHeaderFields,
  27. result.serverReturnJsonString);
  28. }
  29. return nil;
  30. }];

Multipart upload

Due to limited space, for more information about multipart upload, see: Multipart Upload

Resumable upload

NOTE:

  • Currently, resumable upload is applicable only to local files.

  • Resumable upload is not recommended for uploading small and medium-sized files from a mobile client. During resumable upload, a file is uploaded in multiple parts. Therefore, multiple network requests are initiated for a single file, reducing the upload efficiency.**

In a wireless network connection, it usually takes a relatively long time to upload a large file. The upload may fail due to poor network connectivity or network switching. In this case, the entire file needs to be uploaded again. To address this problem, the SDK provides the resumable upload feature.

Before uploading a file, you can specify a folder to save the resumable upload record. If you do not specify the folder, resumable upload takes effect only for the current upload task. When a part of a large file fails to be uploaded due to network errors, only this part is uploaded again, which saves time and reduces traffic consumption. If you specify a folder, the resumable upload record is saved in this folder. If the upload fails, the task needs to be restarted to upload the same file to the same object in the bucket as before. If you choose not to delete the resumable upload record when cancelling the task,the upload starts from the recorded position. For more information, see the following example.

When a resumable upload task fails and is not resumed for a long time, the uploaded parts may become useless parts on the OSS server. In this case, you can set a lifecycle rule for the bucket to clear parts in a timely manner. For more information, see Lifecycle management.

To reduce useless parts, the server deletes uploaded parts if you cancel a resumable upload task. If you want to save the resumable upload record when canceling a resumable task, specify a folder to save the record and change the setting of the deleteUploadIdOnCancelling parameter. If the resumable upload record is saved on the local device for a long time and the parts uploaded to the server are deleted based on the lifecycle rule set for the bucket, the record on the server is inconsistent with the record on the mobile client.

NOTE:

  • Resumable upload is implemented depending on InitMultipartUpload/UploadPart/ListParts/CompleteMultipartUpload/AbortMultipartUpload. If STS authentication is used, add operation permissions for related APIs.

  • Callback notification is also supported for resumable upload and is set in the same way you set it for the preceding upload methods.

  • In resumable upload mode, MD5 check is enabled for each uploaded part by default. Therefore, do not set the Content-Md5 header in the upload request.

Call method for resumable upload with resumable upload records permanently saved on the local device (not saved by default):

  1. OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
  2. resumableUpload.bucketName = OSS_BUCKET_PRIVATE;
  3. //...
  4. NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  5. resumableUpload.recordDirectoryPath = cachesDir;

Resumable upload implementation

  1. // Obtain an UploadId and upload with it. If the task fails and can be resumed, you can upload the same file to the same OSS bucket using the same UploadId.
  2. OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
  3. resumableUpload.bucketName = <bucketName>;
  4. resumableUpload.objectKey = <objectKey>;
  5. resumableUpload.partSize = 1024 * 1024;
  6. resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  7. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  8. };
  9. NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  10. // Set the resumable upload record saving option.
  11. resumableUpload.recordDirectoryPath = cachesDir;
  12. // The value NO indicates that the resumable upload record file is not deleted. The default value is YES, indicating that the resumable upload record file is deleted and the entire file will be uploaded again when the task restarts.
  13. resumableUpload.uploadingFileURL = [NSURL fileURLWithPath:<your file path>];
  14. OSSTask * resumeTask = [client resumableUpload:resumableUpload];
  15. [resumeTask continueWithBlock:^id(OSSTask *task) {
  16. if (task.error) {
  17. NSLog(@"error: %@", task.error);
  18. if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
  19. // If the task cannot be resumed, obtain a new uploadId to upload the file again
  20. }
  21. } else {
  22. NSLog(@"Upload file success");
  23. }
  24. return nil;
  25. }];
  26. // [resumeTask waitUntilFinished];
  27. // [resumableUpload cancel];

Data integrity verification

OSS SDK provides an end-to-end data integrity verification feature based on MD5 and CRC64 to handle the complexities in mobile network environments.

MD5 verification

You must provide the Content-MD5 value to the file during the uploading. Then, the OSS server performs the MD5 verification. The uploading can be successful only when the MD5 value of the file received by the OSS server is equal to the MD5 value provided during uploading, thus guaranteeing the integrity of uploaded data.

  1. OSSPutObjectRequest * request = [OSSPutObjectRequest new];
  2. request.bucketName = BUCKET_NAME;
  3. ...
  4. request.contentMd5 = [OSSUtil fileMD5String:filepath];

CRC verification

Compared with MD5, CRC64 can calculate the CRC value while uploading files.

  1. // Construct an upload request
  2. OSSPutObjectRequest * request = [OSSPutObjectRequest new];
  3. request.bucketName = OSS_BUCKET_PRIVATE;
  4. ///....
  5. request.crcFlag = OSSRequestCRCOpen;
  6. // Enable CRC verification If the data is inconsistent during transmission, OSSClientErrorCodeInvalidCRC is thrown.
  7. OSSTask * task = [_client putObject:request];
  8. [[task continueWithBlock:^id(OSSTask *task) {
  9. // If CRC verification fails, an error is reported
  10. XCTAssertNil(task.error);
  11. return nil;
  12. }] waitUntilFinished];
Thank you! We've received your feedback.