AFNetworking Json发布图片

时间:2016-01-22 04:07:59

标签: ios json afnetworking

我研究了客观的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];

2 个答案:

答案 0 :(得分:0)

请使用以下代码:

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];

希望这有帮助。

答案 1 :(得分:0)

使用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被分成多个数据包。

由于