1

I am trying to upload an image along with some text. I am able to POST the text but somehow the image doesn't reach to server.

Following is my code:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *password = [[Utilities sharedConfiguration] sha1:txtPassword.text];
        NSString *post = [NSString stringWithFormat:@"id_sender=%@&token=%@&array_receiver=%@&message=%@&time_allowed=%@&password=%@",[defaults objectForKey:@"id_user"],[defaults objectForKey:@"token"],selectedContact,txtMessage.text,txtTime.text,password];
        NSLog(@"post %@",post);
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSMutableData *data = [NSMutableData dataWithData:postData];
        //NSMutableData *data = nil;
        if(myimage!=nil){
            NSString *boundary = @"---------------------------14737809831466499882746641449";
            [data appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filetype=\"image/png\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[[NSString stringWithFormat:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [data appendData:[NSData dataWithData:UIImagePNGRepresentation(myimage)]];
        }
        NSString *postLength = [NSString stringWithFormat:@"%d", [data length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:@"https://www.myurl.com/send_message_17294.php"]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:data];

        [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
        [NSURLConnection connectionWithRequest:request delegate:self];
halfer
  • 19,824
  • 17
  • 99
  • 186
pankaj
  • 7,878
  • 16
  • 69
  • 115
  • Possible duplicate of: http://stackoverflow.com/questions/936855/file-upload-to-http-server-in-iphone-programming ? – Jasper Blues Nov 02 '13 at 12:09
  • That url shows how to upload only the image. I want to upload image and some text. Both in same post request. – pankaj Nov 02 '13 at 12:13
  • I think you either need multipart, like that example shows. . or you could base64 encode the image data and embed it in a field. – Jasper Blues Nov 02 '13 at 12:34
  • @pankaj: you can see code example for `base64` string format image. – Maulik Nov 02 '13 at 12:39

2 Answers2

2

You can use AFNetworking so you don't have to digg into the multi-part request format.

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://hostport"]];
NSDictionary *simpleParams = @{ @"key": @"value" };
NSMutableURLRequest* request = [client multipartFormRequestWithMethod:@"POST" path:@"/path" parameters: simpleParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData:fileData
                                    name:@"paramName"
                                fileName:@"filename.png"
                                mimeType:@"image/png"];
    }];

Then create an operation depending on the expected response. For example if you expect JSON:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

    // handle success

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

    // handle error

}];

You can get more information in the AFNetworking documentation.

gimenete
  • 2,649
  • 1
  • 20
  • 16
-1

Try this : Its a Synchronous Request. And image is in base64 string format

    NSString * param = [NSString stringWithFormat:@"%@=%@&%@=%@&%@=%@",
                                @"uphoto",imageData, @"category",categoryName, @"name",FIRSTNAME]; // parameters

    NSData *postData = [param dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://www. ..."];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    [req setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
    [req setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req setHTTPBody:postData];

    NSError *error = nil;
    NSHTTPURLResponse *res = nil;

    NSData *responceData = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&error];
    if (error)
    {
        //handle error        
        return nil;
    }
    else
    {

    }
Maulik
  • 19,348
  • 14
  • 82
  • 137