doukunsan5553 2015-05-04 07:51
浏览 248

使用PHP将base64映像保存到MySQL blob字段

I have this customer that saves files as base64 into a MEDIUMBLOB field (please don't ask why).

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. 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". The original file is ~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:

file_name: 'test.png'
file_ext: 'image/png'
file: https://gist.githubusercontent.com/horgen/25298f2689d9aed865db/raw/gistfile1.txt

The original file: http://cl.ly/image/2o3X3u3a0V0S
The encoded file: http://cl.ly/image/1S3K3v0x0U0p

  • 写回答

3条回答 默认 最新

  • dsrw29618 2015-05-04 08:01
    关注

    Try using readfile(base64_decode($data->file)) instead of echo.

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题