0

I am trying upload an image along with some form fields. I am able to upload image to server using the following link as a reference.

File Upload to HTTP server in iphone programming

But if i try to send some form fields along with the image i am error response. Here is the code i am using

-(void)saveData{
NSString *urlString = @"Sample url";
    NSString *filename = @"filename";
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[self generateDataFromText:FORM DATA IN JSON fieldName:@"add_product"]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"files\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:fileData]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];
    [request setValue:APIKEY forHTTPHeaderField:@"X-API-KEY"];

    NSURLResponse *urlResp;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResp error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSHTTPURLResponse *resp = (NSHTTPURLResponse *) urlResp;
    NSLog(@"status code: %ld, response string: %@",(long)[resp statusCode],returnString);
}

 -(NSMutableData *)generateDataFromText:(NSString *)dataText fieldName:(NSString *)fieldName
{
    NSString *post = [NSString stringWithFormat:@"--AaB03x\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n", fieldName];
    // Get the post header int ASCII format:
    NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    // Generate the mutable data variable:
    NSMutableData *postData = [[NSMutableData alloc] initWithLength:[postHeaderData length]];
    [postData setData:postHeaderData];
    NSData *uploadData = [dataText dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    // Add the text:
    [postData appendData: uploadData];
    // Add the closing boundry:
    [postData appendData: [@"\r\n" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
    // Return the post data:
    return postData;
}

So some one please help me to send form data along with am image to PHP server using POST method. Thanks in advance.

Community
  • 1
  • 1
Gani414
  • 93
  • 2
  • 12

1 Answers1

0

Every Field should be in its own boundary @"\r\n--%@\r\n". So make the following changes to make the code work.

Remove the line:

[postbody appendData:[self generateDataFromText:FORM DATA IN JSON fieldName:@"add_product"]];

And after the line

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

put the following code:

[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; add_product=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[self generateDataFromText:FORM DATA IN JSON] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"\r\n--%@\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

for every field, you need to add these 4 lines.

You should think to use AFNetworking instead. Its easy to work.

Getting it to work with AFNetworking is very easy. Add AFNetworking into your project through Cocoapods, here are the instructions: https://github.com/AFNetworking/AFNetworking

Once AFNetworking is setup, use the following code:

NSString *apiName = URL;

UIImage *yourImage;
NSData *imgData = UIImageJPEGRepresentation(yourImage,1.0);
imgData = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];];

NSData *otherFields = [self generateDataFromText:FORM DATA IN JSON];

NSDictionary * params = [[NSDictionary alloc] initWithObjectsAndKeys:imgData, @"imgFieldName",otherFields,@"add_product",nil]; 

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];



[manager POST:apiName parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {

  //posted successfully


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    //failed

}];

This is very simple Post method with image encoded in Base64. You can add as many fields into params dictionary as needed.

Ahmed
  • 11
  • 2
  • Thanks for the answer. I did the same as you suggested but only image is reaching the server not form fields. Same behaviour earlier also. And can you suggest some tutorials to upload images and form to sever using AFNetworking. – Gani414 Dec 17 '13 at 06:53
  • Getting it to work with AFNetworking is very easy. Add AFNetworking into your project through Cocoapods, here are the instructions: – Ahmed Dec 17 '13 at 07:06
  • I dont see any instructions in your comment. Anyway what is the key in your code? – Gani414 Dec 17 '13 at 07:11
  • Comment was too long, I have edited my last answer to getting it work with AFNetworking. – Ahmed Dec 17 '13 at 07:16