[英]Saving a base64 image to a MySQL blob field with PHP
I have this customer that saves files as base64 into a MEDIUMBLOB field (please don't ask why). 我有这个客户将文件保存为base64到MEDIUMBLOB字段(请不要问为什么)。
The files is saved like this: 文件保存如下:
$file = file_get_contents($_FILES['file']['tmp_name']);
$file = base64_encode($file);
$file = mysql_real_escape_string($file);
$file_name = mysql_real_escape_string($_FILES['file']['name']);
$file_ext = mysql_real_escape_string($_FILES['file']['type']);
$sql = "INSERT INTO $file_table_name (file, file_name, file_ext) VALUES ('$file', '$file_name', '$file_ext')";
This is the code I'm using to force download the file: 这是我用来强制下载文件的代码:
header('Content-type: ' . $data->file_ext);
header('Content-Disposition: attachment;filename="' . $data->file_name . '"');
echo base64_decode($data->file);
die();
For some reason, this works fine with PDF files, but not image files. 出于某种原因,这适用于PDF文件,但不适用于图像文件。 When I try to open the file in Windows Preview it says: "Windows Photo Viewer can't open this picture because the file appears to be damaged, corrupted or is too large". 当我尝试在Windows预览中打开文件时,它说:“Windows Photo Viewer无法打开此图片,因为该文件似乎已损坏,损坏或太大”。 The original file is ~150KB. 原始文件大约150KB。
If I do this; 如果我这样做;
echo '<img src="data:' . $data->file_ext . ';base64,'.$data->file.'" />';
die();
...the image looks fine and I'm able to save the image (save as) without issues. ...图像看起来很好,我可以保存图像(另存为)而不会出现问题。
Anyone know what I'm doing wrong? 谁知道我做错了什么? Am I missing any headers? 我错过任何标题吗?
Update with values from the DB: 使用DB中的值更新:
file_name: 'test.png' file_name: 'test.png'
file_ext: 'image/png' file_ext: 'image / png'
file: https://gist.githubusercontent.com/horgen/25298f2689d9aed865db/raw/gistfile1.txt 文件: https : //gist.githubusercontent.com/horgen/25298f2689d9aed865db/raw/gistfile1.txt
The original file: http://cl.ly/image/2o3X3u3a0V0S 原始文件: http : //cl.ly/image/2o3X3u3a0V0S
The encoded file: http://cl.ly/image/1S3K3v0x0U0p 编码文件: http : //cl.ly/image/1S3K3v0x0U0p
尝试使用readfile(base64_decode($ data-> file))而不是echo。
You could try 你可以试试
echo base64_decode(str_replace(' ', '+', $data->file));
See the PHP manual page for base64_decode() and also the comments on the page. 请参阅PHP手册页以获取base64_decode()以及页面上的注释。
Yeah.. This is akward.. I found the problem. 是的..这很尴尬..我发现了问题。 This is a Wordpress site and I have this functions.php file where I include all my functions. 这是一个Wordpress网站,我有这个functions.php文件,其中包含我的所有功能。 For some reason the previous developer on this project included a php file inside functions.php. 出于某种原因,该项目的前任开发人员在functions.php中包含了一个php文件。 The included file had some whitespace/tab before the "php"-tag and this generated a newline in the decoded file :S 包含的文件在“php”-tag之前有一些空格/制表符,这在解码文件中生成了一个换行符:S
Anyways, thank you all for trying to help me :) 无论如何,谢谢大家试图帮助我:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.