1

I am uploading an image to PHP from an iPhone but in PHP the image is not visible. The image was saving in bytes.

  -(void)uploadMyImage:(UIImage *)img
    {
        NSData *data = UIImageJPEGRepresentation(img, 90);
        NSMutableString *urlString = [[NSMutableString alloc] init];
        [Base64 initialize];
        [urlString appendFormat:@"image=%@",[Base64 encode:data]];
          NSString *baseurl = @"http://projectleads.info/spirits/images/imageupload1.php"  ;
        NSData *postData = [urlString dataUsingEncoding:NSUTF8StringEncoding];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
        NSURL *url = [NSURL URLWithString:baseurl];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
        [urlRequest setHTTPMethod: @"POST"];
        [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [urlRequest setValue:@"application/x-www-form-urlencoded"
          forHTTPHeaderField:@"Content-Type"];
        [urlRequest setHTTPBody:postData];
        NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
        [connection start];
        }

  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        resData=[[NSMutableData alloc]init];
    }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [resData appendData:data];
    }
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSString* newStr = [[NSString alloc] initWithData:resData
                                                 encoding:NSUTF8StringEncoding];
    }

And my php code is

<?php
    $base=$_REQUEST['image'];
     if(empty($base))
    {
        echo 'No data';
    }
    else
    {
    echo $base;
    $binary=base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');
        // print($binary);
    //$theFile = base64_decode($image_data);
    $dbser='localhost';  
    $dbuser='spirit';
    $dbpwd='123456';
    $dbname='spirit';
       $db= mysql_connect($dbser,$dbuser,$dbpwd);
     $dbcon=mysql_select_db($dbname);
     function generate_chars()
    {
        $num_chars = 4; //max length of random chars
        $i = 0;
        $my_keys = "123456789abcdefghijklmnopqrstuvwxyz"; //keys to be chosen from
        $keys_length = strlen($my_keys);
        $url  = "";
        while($i<$num_chars)
        {
            $rand_num = mt_rand(1, $keys_length-1);
            $url .= $my_keys[$rand_num];
            $i++;
        }
        return $url;
    }

     function isUnique($chars)
    {
        //check the uniqueness of the chars
        global $link;
        $q = "SELECT * FROM `url` WHERE `randname`='".$chars."'";
        $r = mysql_query($q, $link);
        //echo mysql_num_rows($r); die();
        if( mysql_num_rows($r)>0 ): 
            return false;
        else: 
            return true;
        endif;
    }

     $chars = generate_chars();
     while( !isUnique($chars) )
     {
            $chars = generate_chars();
     }
    $query=mysql_query("insert into url (randname) values ('".$chars."')");
    $test=$chars.".jpg";
    $file = fopen($test, 'wb');
    fwrite($file, $binary);
    fclose($file);
    echo 'success';
    echo '<img src=test.jpg>';
    }

?>

2 Answers 2

0

For iPhone :

Check here How to upload Image on PHP Server

Also this Upload Image

And For converting UIImage into String using Base64 Ecoding use Base64 Ecoding Method

I hope this will helps You

14
  • final string response are coming in the formate of base 64 and image also saving in server but it is not visible. Jan 30, 2013 at 6:43
  • decode Base64 String into UIImage it gives u same Image that u uploaded I think Jan 30, 2013 at 6:58
  • No i am not decoded base 64 string to uiimage the string response are coming from server Jan 30, 2013 at 7:01
  • I think your client side coding in now working fine now. There is a problem on Server side. Jan 30, 2013 at 7:02
  • and what they receive in response?? Jan 30, 2013 at 7:04
0

Your PHP code is just fine, the problem is in the base 64 encoding. I have successfully uploaded an image with your code, do the following to correctly encode the data.

Copy and paste this method in your code (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];
}

Now to get the encoded string do

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

Append the encoded string as follows

[urlString appendFormat:@"image=%@", encodedString];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.