r_robotics
r_robotics

Reputation: 51

Retrieve HTTP POST variables using multipart/form-data sent from an iOS device

I need to retrieve the POST variables being sent from my iOS application, but so far I have had no luck. Here is some background:

I have an iOS application that posts an image along with some variables to a php page that simply saves the variables in a file (for debugging) and moves the image to the current directory (server side). I can get a handle on the image without issue using the $_FILE variable, however I cannot seem to get any of the POST parameters at all.

Some general info and what I've tried:

I'm using modified sample code from here

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

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

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

// string constant for the post parameter 'file'
NSString *FileParamConstant = @"media";

//Setup request URL
NSURL *requestURL = [[NSURL alloc] initWithString:@"http://myWebAddress/myAction.php"];

// 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([self.imageButtonOutlet backgroundImageForState:UIControlStateNormal], 1.0);
if (imageData) {
    printf("appending image data\n");
    [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:[@"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];

NSURLConnection *postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[postConnection start];
[postConnection release];

Also, here is myAction.php, as it stands right now:

<?php

$fp_file = fopen("./output_files.txt", "w");
$fp_post = fopen("./output_post.txt", "w");

$post_content = var_export($_POST , TRUE);
$file_content = var_export($_FILES, TRUE);
fwrite($fp_file, $file_content);
fwrite($fp_post, $post_content);


fclose($fp_file);
fclose($fp_post);

move_uploaded_file( $_FILES['media']['tmp_name'], "test.jpg");

?>

Upvotes: 2

Views: 5267

Answers (3)

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

use following code to upload i have made change only at last line of this function, you can set delegates for NSURLConnection according to your requirement.

-(void)upload
{
    // create request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:30];
    [request setHTTPMethod:@"POST"];

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

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

    // string constant for the post parameter 'file'
    NSString *FileParamConstant = @"media";

    //Setup request URL
    NSURL *requestURL = [[NSURL alloc] initWithString:@"http://myWebAddress/myAction.php"];

    // 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([self.imageButtonOutlet backgroundImageForState:UIControlStateNormal], 1.0);
    if (imageData) {
        printf("appending image data\n");
        [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:[@"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];

    NSURLResponse *response = nil;
    NSError *err = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSString *str = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
    NSLog(@"Response : %@",str);
}

and in myAction.php file write following PHP code to read your parameters

<?php
    echo "FileType :". $_FILES["media"]["type"] ;
    echo "FileName :". $_FILES["media"]["name"] ;
    echo "FileSize :".($_FILES["media"]["size"] / 1024)/100 ;
    echo "Version :".$_REQUEST["ver"];
    echo "Language :".$_REQUEST["lan"];
?>

Upvotes: 0

r_robotics
r_robotics

Reputation: 51

After 4 hours of debugging, the problem was in my php code... which has been edited to reflect the change. the variable $post_content was created with the name $post_contnet. Hopefully this will at lease serve as code guide to others trying to implement a similar service.

You can't fix stupid.

Upvotes: 1

yc.lin
yc.lin

Reputation: 379

Is there any reason for implementing the HTTP protocol yourself?

There are several networking packages out there

https://github.com/AFNetworking/AFNetworking

supports multi-part form data I believe.

Upvotes: 0

Related Questions