3

I want to upload image using POST method. I can upload the image separately. But I want to post them to the server along with other data which I need to send. Can anyone please help me.know how to post

Here is the code where I send my data. Along with this,I need to send the image along with this

postString = [NSString stringWithFormat:@"u=TuNmae&p=pass&o=onr&j=123&a=321&d=8765&t=123&at=need&image="];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url1];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];

    [req addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];

    webData = [[NSMutableData data] retain];
    [webData appendData:returnData];
    NSLog(@"attempt%@",webData);
    NSString *webResult;
    webResult = [[NSString alloc] initWithData:webData encoding:NSASCIIStringEncoding];

    webResult = [webResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSLog(@"str %@",webResult);

I need to insert the image into the postString. The last parameter.

rakendu
  • 73
  • 2
  • 6
  • Can you provide a little more information? Are you talking native application? UIWebView/Web-app? – TNC Feb 21 '11 at 12:38
  • No I am not using uiwebView. I have few details(strings) along with it, I need to send the image too. Please help – rakendu Feb 21 '11 at 14:00
  • @rakendu i also have same problem if you get solve please let me know – Harish Sep 16 '11 at 09:12

3 Answers3

1

You must set the enctype form atribute to "multipart/form-data"

form enctype="multipart/form-data"

then you can upload file input and other text or hidden input in same form adn same submit.

in your api do this


NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];


    //file data
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"ImageFile.png"];
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:fullPathToFile];

AmirModiri
  • 755
  • 1
  • 5
  • 13
0

I also wanted to upload an image along with other data in the same POST, most information about uploading images is just for uploading an image alone in one server connection, here is how I solved this.

This is the PHP

<?php
/* As you can see there are more values not only the image */
$variableOne    = $_POST['variableOne'];
$variableTwo    = $_POST['variableTwo'];
$variableThree  = $_POST['variableThree'];
$variableFour   = $_POST['variableFour'];
$variableFive   = $_POST['variableFive'];
$variableSix    = $_POST['variableSix'];
$variableSeven  = $_POST['variableSeven'];
$variableEight  = $_POST['variableEight'];
$variableNine   = $_POST['variableNine'];
$variableTen    = $_POST['variableTen'];

/* Our image */
$image = $_REQUEST['image'];

/* This is for trying to get a unique name for the image file, since maybe you want to store large amount of images */
$currentDate = date("Y-m-d");
$name  = "" . $currentDate . microtime() . rand(0, 999) . rand(0, 999) . rand(0, 999) . ".jpg";

/* 
 * Here comes the image stuff
 */
if (file_exists($name)) {
    echo "File already exists";
} else {
        /* Decoding image */
        $binary = base64_decode($image);

        /* Opening image */
        $file = fopen($name, 'wb');

        /* Writing to server */
        fwrite($file, $binary);

        /* Closing image file */
        fclose($file);

        echo "Added";
    }   
}   
?>

Then in Xcode copy and paste this method (taken from Creating a base-64 string from NSData)

- (NSString*)base64forData:(NSData*) theData {
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }

        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

In YourViewController.h file

@interface YourViewController : UIViewController {
    NSURLConnection *serverConnection;
    NSMutableData *returnData;
}

This is the server connection code

NSURL *sendURL = [NSURL URLWithString:@"http://yourdomainname/imagefolder/phpscript.php"];

NSMutableURLRequest *sendRequest = [NSMutableURLRequest requestWithURL:sendURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];

[sendRequest setHTTPMethod:@"POST"];

[sendRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

NSData *imageData = UIImageJPEGRepresentation(yourImage, 1.0);

NSString *encodedString = [[self base64forData:imageData] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];

NSString *dataToSend = [[NSString alloc] initWithFormat:@"variableOne=%@&variableTwo=%@&variableThree=%@&variableFour=%@&variableFive=%@&variableSix=%@&variableSeven=%@&variableEight=%@&variableNine=%@&variableTen=%@&image=%@", valueOne, valueTwo, valueThree, valueFour, valueFive, valueSix, valueSeven, valueEight, valueNine, valueTen, encodedString];

[sendRequest setHTTPBody:[dataToSend dataUsingEncoding:NSUTF8StringEncoding]];

serverConnection = [[NSURLConnection alloc] initWithRequest:sendRequest delegate:self];

[serverConnection start];

Set delegate methods for server connection

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    returnData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [returnData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (connection == serverConnection) {
        NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

        NSLog(@"Response: %@", responseString);

        if ([responseString isEqualToString:@"Added"]) {

            /* Make something on success */

        } else {

            /* Make something else if not completed with success */

        }
    }
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    /* Make something on failure */
}
Community
  • 1
  • 1
Carlo Espino
  • 1,354
  • 1
  • 15
  • 21
0

Rakendu try like following way you can send by this one...

NSString *url = @"www.google.com";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

[request setHTTPMethod: @"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDARY];  
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];  

NSMutableData *body = [NSMutableData data];

[self addToDataField:body field:@"firstname" value:txtFirstName.text];
if (updatedImage == TRUE)
        {

    [body appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@\r\n",BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
    [body appendData:UIImagePNGRepresentation(image)];  
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];  

    updatedImage = FALSE;
    }
    NSLog(@"%@",body);

NSString *temp =  [NSString stringWithFormat:@"%i", [body length]];
[request setHTTPBody:body];
[request setHTTPMethod: @"POST"];
[request addValue:temp forHTTPHeaderField:@"Content-Length"];

NSLog(@"%@",request);

NSError *error = nil;
NSURLResponse *response;
urlData = [[[NSMutableData data] retain] autorelease];
urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

Hope this one is help to you..

AJPatel
  • 2,291
  • 23
  • 42