The personal information pages in the app usually have the function of setting avatar. When the user selects an image from the album or takes a photo successfully, he or she generally needs to send the photo to the server for saving, so that the user can request the photos from the server again on other devices or log in again. The project is very convenient to implement through AFN.
- (void)upload{ NSData *imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"" ofType:nil]]; NSDictionary* URLParameters = @{//Set request header }; NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"" ofType:nil]]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLResponse *repsonse = nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil]; NSString *mimeType = ; NSLog(@"%@", ); [[AFHTTPSessionManager manager] POST:@"Upload URL" parameters:URLParameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithFileData:imageData name:@"file" fileName:@"" mimeType:mimeType]; } progress:^(NSProgress * _Nonnull uploadProgress) { // } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //Processing successfully } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //Processing failed }]; }
It is an image that exists in the project, and it will exist in the form of NSBundle when compiling. First, send the request synchronously through NSURLConnection to obtain the MIMEType. Then, using AFN, you can place the imageData that needs to be uploaded through the method appendPartWithFileData: in the request body, and then pass in the MIMEType that has been obtained, and upload it smoothly.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.