Dave
Dave

Reputation: 21

How to store Base64 string in mySQL as BLOB

I'm trying to insert a base64 string into blob by using the code below, I'm getting a blob added to the database but it's a damaged file with no extension.

Background:

[request setHTTPMethod:@"POST"];
NSString *encodedString = [binaryData base64Encoding];
NSString *bodyString = [NSString stringWithFormat:@"image=%@", encodedString];

PHP:

$json_obj = $_POST['image'];
$encodedData = str_replace(' ','+',$json_obj);
$encodedData= chunk_split(base64_encode(file_get_contents($encodedData)));
$blob = $encodedData;
$dbHandle = mysql_connect("--------","-------","------");
$dbFound = mysql_select_db("----------");

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 '<img src="data:image/jpeg;base64,' . $blob . '" />';
}
else{
      print "No Connection";
}

Upvotes: 2

Views: 8339

Answers (2)

eric
eric

Reputation: 11

Have you tried using mysql base64 function: TO_BASE64('string'); ?

Upvotes: 1

Boris
Boris

Reputation: 802

Try to use:

$encodedData= chunk_split(base64_encode(file_get_contents($json_obj)));

Then change echo "BLOB: " . "---" . $blob; to:

echo '<img src="data:image/jpeg;base64,' . $blob. '" />';

Otherwise you are just dumping the string value that's why you get this result.

Upvotes: 4

Related Questions