0

Guys i'm trying to send a image to server and its working perfectly when i try to send that in Postman. But when i try to implement the same in my IOS code. There i don't receive the desired result. Below is the IOS code to add file, rest headers/URL parameter are working fine.

NSData *postData;
postData =[[NSString stringWithFormat:@"Content-Disposition: form-data; content=\"%@\"", pBytes] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
theConnection = [NSURLConnection connectionWithRequest:request delegate:self];

Here is the Postman screenshot (https://www.dropbox.com/s/r8ar1pr0k4s3qqm/Screen%20Shot%202016-06-23%20at%2010.15.54%20AM.png?dl=0). In the screenshot the image is added as file. What additions shall i do in the code to achieve the same results as Postman.

Any help will be appreciated

Bagus Cahyono
  • 668
  • 2
  • 8
  • 17
gurmandeep
  • 1,227
  • 1
  • 14
  • 30
  • Here is my answer for the same. http://stackoverflow.com/questions/37590959/upload-image-to-server-through-post-method-ios/37593645#37593645 – Bhadresh Mulsaniya Jun 23 '16 at 05:06

2 Answers2

0

If your using AFNetworking use this code,

 NSData *data1 = UIImagePNGRepresentation (self.myimageView.image);

 NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
 [parameters setObject:firstnametf.text forKey:@"FirstName"];
 [parameters setObject:lastnametf.text forKey:@"LastName"];
 [parameters setObject:emailtf.text forKey:@"Email"];

 [parameters setObject:data1 forKey:@"Photo"];



 AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:@"URL"];

 [manager POST:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                        //do not put image inside parameters dictionary as I did, but append it!

                        [formData appendPartWithFileData:data1 name:@"Photo" fileName:@"Image.png" mimeType:@"image/png"];

                    } success:^(NSURLSessionDataTask *task, id responseObject)
                     {

                         NSLog(@"JSON: %@", responseObject);
                         //here is place for code executed in success case

                     }  failure:^(NSURLSessionDataTask *task, NSError *error) {

                         //here is place for code executed in success case
                         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error while sending POST"
                                                                             message:@"Sorry, try again."
                                                                            delegate:nil
                                                                   cancelButtonTitle:@"Ok"
                                                                   otherButtonTitles:nil];
                         [alertView show];

                         NSLog(@"Error: %@", [error localizedDescription]);
                     }];

hope its helpful

Iyyappan Ravi
  • 3,205
  • 2
  • 16
  • 30
0

Use this Code, But the below code is old format my suggestion is above answer is new,

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = [NSString stringWithString:@"file"];

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""]; 

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];                                    
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];

hope its helpful

Iyyappan Ravi
  • 3,205
  • 2
  • 16
  • 30