0

我正在尝试iOS使用 PHP 将新图片从数据库发送到数据库。

我在...中得到一个零字节BLOB任何DATABASE帮助将不胜感激:)

代码:

NSString *url = @"-----------------";

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];

[request setHTTPMethod:@"POST"];

NSData *binaryData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [binaryData base64Encoding];
//NSLog(@"Encoded : %@ ",encodedString);
//NSData* binaryData = UIImagePNGRepresentation(image);

NSString *bodyString = [NSString stringWithFormat:@"image=%@",encodedString];
[request setValue:[NSString stringWithFormat:@"%d", [bodyString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[bodyString dataUsingEncoding:NSASCIIStringEncoding]];//or set the type of encoding agreed with your webservice

NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *responseString;
if ( responseData && !error){
    responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Response: %@",responseString);
}

PHP:

$json_obj = json_decode($_POST['image']);
$blob = base64_decode($json_obj);

$dbHandle = mysql_connect("MYCONNECTION");
$dbFound = mysql_select_db("MYCONNECTION");

if($dbFound){

    $check = "INSERT INTO `Images`(`imageId`, `image`, `userId`, `dateCreated`) ".
             "VALUES ".
             "('','$blob','0',null)";

    $retval = mysql_query( $check, $dbHandle );

    if(!$retval)
    {
        die('Could not enter data: ' . mysql_error());
    }
   echo "BLOB: " . $blob;
}
else{
  print "No Connection";
}

mysql_close($dbHandle);
?>

我得到的输出:

Response: BLOB: 

并在数据库中获取新的 BLOB

[BLOB - 0B]
4

1 回答 1

0

对于发布方法,请阅读我自己的答案。

并使用此代码发布图片。

NSString  *imgPath = fullPathOfYourImage;
    if([[NSFileManager defaultManager] fileExistsAtPath:imgPath])
    {
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];                                                        
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\"; filename=\"YourImageName.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
                                                                                                               ^..YourImageName….^

        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithContentsOfFile:imgPath]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    }
于 2013-03-16T06:43:12.357 回答