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 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图