Uploading an image to Parse.com using AFNetworking causing a corrupted image

I am trying to upload images to Parse.com using AFNetworking 2.0. When I upload an image that was saved in "Parse", then the resulting file is corrupted.

Performing diff, I see that the following data has been added to the beginning:

enter image description here

'Boundry' data is also added at the end of the file.

What am I doing wrong? Mime type?

I am sending the same file using 'curl' and everything is fine.

This is the code I use to send:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];

[manager.requestSerializer setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];

[headers enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
    [manager.requestSerializer setValue:value forHTTPHeaderField:key];
}];

[manager POST:@"https://api.parse.com/1/files/imagefile.jpg"
   parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
      {
          NSData *imgData = UIImageJPEGRepresentation(image, 1.0f);

          [formData appendPartWithFileData:imgData
                                      name:@"imagefile"
                                  fileName:@"imagefile.jpg"
                                  mimeType:@"image/jpeg"];
      }
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          success(operation, responseObject);
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          failure(operation, error);
      }
 ];

UPDATE

The following code works as expected (not multi-part, so it is clear that this is a problem area):

NSMutableString *urlString = [NSMutableString string];
[urlString appendString:@"https://api.parse.com/1/"];
[urlString appendFormat:@"files/imagefile.jpg"];

NSURL *url = [NSURL URLWithString:urlString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"***********" forHTTPHeaderField:@"X-Parse-Application-Id"];
[request addValue:@"***********" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[request addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:UIImageJPEGRepresentation(image, 0.3f)];

NSURLResponse *response = nil;
NSError *error = nil;

[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSString *fileUrl = [httpResponse allHeaderFields][@"Location"];
+3
source share

All Articles