4

I am trying to add an Image into my JSON file that I want to post on the server. I am using the following code but I keep on getting Invalid type in JSON write (NSConcreteMutableData) error. The code is

NSDictionary *parameter = [[NSDictionary alloc]init];
NSData *imageData = UIImagePNGRepresentation(imageView.image);
parameter = @{@"body":@"Hi",@"image":imageData};

Also, I am using AFNetworking to post the image to the server

I am not sure what is wrong in the code. Any help would be highly appreciated

Jonathan
  • 2,728
  • 10
  • 43
  • 73

2 Answers2

3

If someone else has the same problem later. this is the code that you should use

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSDictionary *parameter = @{@"body":@"image"};
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:parameter constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

Source : link

Jonathan
  • 2,728
  • 10
  • 43
  • 73
  • Where did you specify that multipart in the block correspond to the key 'image'? With the line 'NSDictionary *parameter = @{@"body":@"image"};', image is a value for body key. – OutOnAWeekend Apr 18 '13 at 10:38
  • @AnandKumar read it carefully once, its all there. the very next line defines it. here I assigned my body the value "Image" (which is a string), below that I add the @"avatar" which is the MultipartFormData – Jonathan Apr 18 '13 at 11:48
  • @Jonathon Thanks for the reply. But as your initial question, didn't you actually want the image data to go as the value for a key named 'image'? As per your initial question, 'image' is a key and not a value of another key. – OutOnAWeekend May 07 '13 at 06:44
1

try like this ,

parameter = @{@"body":@"Hi",@"image":[NSString stringWithFormat:@"%@" ,imageData]};
Balu
  • 8,470
  • 2
  • 24
  • 41
  • Sunny, wont this send the image as a string to the server? it should be a File for the server to accept it, or else I get an error – Jonathan Mar 26 '13 at 07:02
  • once see this one http://stackoverflow.com/questions/2426755/how-to-upload-image-to-remote-server-in-iphone – Balu Mar 26 '13 at 07:04