I have BLOB information from my database and trying to display a PDF file in browser using this:
echo "<object data='data:application/pdf;base64,".base64_encode($row['PDF_File'])."' type='application/pdf' style='height:600px;width:60%'></object>";
But with the result I get a problem like this:
The error message (originally in Russian) in English is:
Error
The PDF document could not be loaded.
To reboot
If I change base64_encode
to base64_decode
it will crack, if I delete this, it won’t show up.
New PDFs are added to DB by JavaScript script:
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
console.log(reader.result);
const data = {
file_pdf: reader.result
};
sendForm(data);
};
What can I do to solve this?
2
Answers
Thanks a lot to Giacomo1968.
I found out that in
<object>
line with metadata duplicates thedata:application/pdf;base64,
already in the database field. So we need just remove that part.Turns into:
This answer on StackOverflow explains the issue.
One idea of how to get the PDF is creating a PHP file that directly downloads the PDF file like this:
Or you can try to force a download by adding the
Content-Disposition
header like this; change the value of$filename
to be whatever the filename should be:Update 1: Based on the original poster’s comments:
If that is the case, you don’t have to use
base64_encode
again. Just change your line to the following; removing thatbase64_encode
:Or using my example with the download, change it to the following; note I am using
base64_decode
for theecho
line to properly decode the Base64:Update 2: If none of above works, my only guess is the JavaScript upload process is messed up. Or the database storage is messed up. Instead of
BLOB
for DB storage, tryLONGTEXT
for storage because you are not storing binary data but a very long Base64 encoded text string.