preface

Recently, when I was working on a project, the person in the background said that the avatar should be uploaded through OSS when modifying personal information. I was like, what is this? Is this some kind of protocol? A quick check revealed it wasn’t, but there wasn’t much to go on beyond Alibaba’s official documents. So I had to explore it step by step, and write it down and hope it would be useful.

  • What is OSS and what are its benefits?

To put it simply, OSS is a service that stores data on Alibaba’s servers (hereinafter referred to as cloud services).

Benefits:

  1. The cost is low

Its charging rules:

You do not need to purchase storage and traffic capacity in advance. With the development of your business, you will enjoy more infrastructure cost advantages.

The benefits are obvious, low charge, reduce the pressure of our background server (hereinafter referred to as the back service).

  1. Data security, multiple backups.
  2. Data processing services. Image processing, audio and video transcoding, content accelerated distribution, yellow authentication services, archiving services, etc.
  3. Automatic data management life cycle, etc.
  • OSS Process Principles

Without OSS, if we want to upload photos to the back server, we just need to make a request.

// 1. Image processing // 2. Upload to serverCopy the code

With OSS, two requests need to be made.

2. Upload the image to the cloud server and join the image path URL // 3. The image parameter in the back-end service interface should be NSString. Upload the URL stitched in step 2 as a parameter to the back-end serviceCopy the code

The use of OSS

  1. The preparatory work

Opening OSS and configuring cloud services are usually handled by people in the background.

So ask someone backstage, get AccessKey and SecretKey. There are also buckets (storage space, equivalent to a home directory), and endpoints (access to domain names) for both the internal and external networks.

The difference between the internal network and the external network lies in that the internal network is used between the same Bucket Ali cloud products, such as taking pictures for analysis and so on. The extranet is where we upload images to the cloud and different buckets and things like that. This paper explores the operation of uploading pictures on the Internet.

  1. Upload photos

Go straight to code

@interface FHProfileInfoViewModel()

@property (nonatomic, strong) OSSClient *client;

@end

@implementation FHProfileInfoViewModel

- (void)aliyunWithFileName:(NSString *)fileName {

    [MBProgressHUD fh_showMessage:@"Under modification"];
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = @"BucketName for your project, which is the home directory."; // objectKey is the name of the file stored in the cloud service. UIImage *testImage = [UIImage imageNamed:@"test"];
    NSData *testData = UIImageJPEGRepresentation(testImage, 0.1);
    put.uploadingData = testData; // put. UploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) { // NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//    };
    OSSTask * putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if(! task.error) { NSLog(@"upload object success!"); [MBProgressHUD fh_hideHUD]; // 1. Connect url // 2.else {
            NSLog(@"upload object failed, error: %@" , task.error);
            [MBProgressHUD fh_hideHUD];
            [MBProgressHUD fh_showError:@"Modification failed"];
        }
        returnnil; }]; // Can wait for the task to complete [putTask]waitUntilFinished];
}

- (OSSClient *)client {
    if(! _client) { NSString *endpoint = @"The endpoint of your project";
        NSString *accessKeyid = @"AccessKeyid for your project";
        NSString *secretKeyId = @"SecretKeyId of your project";
        NSString *securityToken = @""; / / can empty the backend id < OSSCredentialProvider > the credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId: accessKeyid secretKeyId:secretKeyId securityToken:securityToken]; _client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential]; }return _client;
}

@end
Copy the code

1 one official document suggests OSSClient global one, pay attention to the configuration of the corresponding data.

2 discount ️objectKey is the file name.

3 ⃣ [putTask waitUntilFinished]; Similar to the GCD railing function. Here, it is called because it needs to join the URL after the successful upload and then upload it to the background.

4 discount ️ Finally, url splicing after successful uploading.

At the beginning of the test, found that the successful upload callback, did not find. There’s no tutorial on the Internet. Later, I heard the big guy say that I knew it was so.

    NSString *picUrlStr = [NSString stringWithFormat:@"http://%@.%@/%@", bucketName, endpoint, objectName]; / / that"http://" + bucketName + "." + this.endpoint + "/" + objectName;
Copy the code

Let me tell you something special

  1. There is no such thing as a folder in OSS services. But we can name objectName with a/(it can’t start with a “/” or “”), just like folder management.

  2. If a file with the same objectName is passed, it will be overwritten.

  3. If the image file name is not appended with.png, it will be downloaded directly when opened in the browser. If you add it, it will show you.

– (void)sd_setImageWithURL (nullable NSURL *) URL placeholderImage (nullable UIImage *)placeholder

So the name is a matter of opinion. If necessary, discuss naming rules with the backend and Android people.