从iPhone上传图像到PHP

时间:2013-01-30 06:25:21

标签: php iphone ios objective-c

我正在从iPhone上传图像到PHP但在PHP中图像不可见。图像以字节保存。

  -(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];
    }

我的PHP代码是

<?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 个答案:

答案 0 :(得分:0)

对于iPhone:

点击此处How to upload Image on PHP Server

Upload Image

使用Base64 Ecoding将UIImage转换为String使用Base64 Ecoding Method

我希望这会对你有所帮助

答案 1 :(得分:0)

你的PHP代码很好,问题在于base 64编码。我已成功使用您的代码上传了一张图片,请执行以下操作以正确编码数据。

将此方法复制并粘贴到您的代码中(取自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];
}

现在获取编码的字符串

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

附加编码的字符串如下

[urlString appendFormat:@"image=%@", encodedString];
相关问题