AFNetworking Json 发布图片

Posted

技术标签:

【中文标题】AFNetworking Json 发布图片【英文标题】:AFNetworking Json post image 【发布时间】:2016-01-22 04:07:58 【问题描述】:

我学习的是客观 C 编程。我不知道如何将图像从库中发布到 api json(我从库中使用 UIImagePickerController 拍摄了图片)。谢谢!

我的 json api: http://i.stack.imgur.com/DLKZG.png

- (IBAction)btnAddBook:(id)sender 


AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://192.168.1.54"]];

NSData *imageData = UIImageJPEGRepresentation(self.ivPickedImage.image, 1);
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];

[params setValue:self.tfTitle.text forKey:@"title"];
[params setValue:self.tfPrice.text forKey:@"price"];
[params setValue:self.tfProem.text forKey:@"proem"];
[params setValue:@"Vietnamese" forKey:@"language"];

AFHTTPRequestOperation *op = [manager POST:@"/api/books" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 

    [formData appendPartWithFileData:imageData name:@"file" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
 success:^(AFHTTPRequestOperation *operation, id responseObject) 
    NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
 failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    NSLog(@"Error: %@ ***** %@", operation.responseString, error);
];
[op start];

【问题讨论】:

【参考方案1】:

请使用以下代码:

NSDictionary *requestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:abc.text, @"firstkey",xyz.text, @"secondkey" nil];

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"YOUR API URL" parameters:requestDictionary constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                                                      [formData appendPartWithFileData:imageData name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    
     error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;

    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) 
             NSLog(@"%@", response);
            if (error) 
             else 
            
];
[uploadTask resume];

希望这会有所帮助。

【讨论】:

【参考方案2】:

通过使用AFNetworking 多部分请求。您可以将图像作为数据发布。以下是如何使用 AFNetworking 将图像作为多部分发布的完整块

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
     error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) 
                      // This is not called back on the main queue.
                      // You are responsible for dispatching to the main queue for UI updates
                      dispatch_async(dispatch_get_main_queue(), ^
                          //Update the progress view
                          [progressView setProgress:uploadProgress.fractionCompleted];
                      );
                  
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) 
                      if (error) 
                          NSLog(@"Error: %@", error);
                       else 
                          NSLog(@"%@ %@", response, responseObject);
                      
                  ];

    [uploadTask resume];

AFNetworking

这里你的图片不是JSON。通过使用 AFNetworking 多部分请求,您的所有请求参数都以JSONImage/Video 的形式传递,它们以NSData 的形式传递。其中 NSData 分为多个数据包。

谢谢

【讨论】:

以上是关于AFNetworking Json 发布图片的主要内容,如果未能解决你的问题,请参考以下文章

iOS-AFNetworking3.0上传大量(1000张)图片到服务器

AFN3.0封装

AFNetworking Json 发布图片

AFN2.0到3.0的迁移

AFNetworking 2.0 图片上传和 JSON 返回错误

iOS开发之AFN的基本使用