Hayden Passmore
Hayden Passmore

Reputation: 1155

Pulling pdf BLOB from database using php and displaying it in a html page not working

I am trying to retrieve a blob pdf then display it on the page. I am using the following code however only the base 64 string is being displayed instead of the pdf which is my desired output.

The following is the code that I am using.

<?php
    //header('Content-type: application/pdf');
    require 'connect.php';
    $db=mysqli_connect($mysql_host, $mysql_user, $mysql_password,$mysql_dbName);
    $sql = "SELECT * FROM files WHERE id = 1688";
    $sth = $db->query($sql);
    $result=mysqli_fetch_array($sth);
    $pdf = base64_encode($result['file']);
    echo $pdf;
?>
<object data="<?php echo $pdf ?>" type="application/pdf"></object>

I have tried using

<object data="data:application/pdf;base64,<?php echo base64_encode(content) ?>" type="application/pdf" style="height:200px;width:60%"></object>

And also putting it in an iframe like this

<object data="data:application/pdf;base64,<?php echo base64_encode($result['file']) ?>" type="application/pdf">
    <iframe src="data:application/pdf;base64,<?php echo base64_encode($result['file']) ?>"></iframe>
</object>

But the pdf file fails to load.

-----------EDIT 5/8/17--------

I am now adding an iframe dynamically using the code below yet I get an error saying that

Resource interpreted as Document but transferred with MIME type application/pdf:

here is my newly added javascript

var iframe = document.createElement('iframe');

var src = $('#hiddenBase64').val();//this stores the base64 string

$(iframe).width("100%");

$(iframe).height("100%");

iframe.src = "data:application/pdf;base64," + src;

document.body.appendChild(iframe);

Thanks for any help.

Upvotes: 0

Views: 3027

Answers (2)

Hayden Passmore
Hayden Passmore

Reputation: 1155

So I wasn't really getting anywhere with this and have read Here that it is bad practice to store files in the database. (I wasn't able to figure out why the pdf failed to load)

What I am doing now is storing the file in a subfolder on my server. Then I am storing a link to the file in the database and to display the file I just run a select query that pulls the link and then I have the link.

Upvotes: 0

Ronald Swets
Ronald Swets

Reputation: 1667

Remove the echo $pdf. This will output the base64_encoded pdf before the as well.

Upvotes: 1

Related Questions