将BLOB图像从PHP中的数据库保存到磁盘
问题描述:
我已将图像作为BLOB文件存储在我的数据库中。这可能不是最好的做法(我知道这一点)。我想在点击时在页面上创建一个链接,并提示用户使用典型的保存文件提示,这样他们就可以将文件保存在他们的个人磁盘上。将BLOB图像从PHP中的数据库保存到磁盘
我在网上进行了研究,但我所尝试的似乎不工作,它只是将字节发布到我的页面而不是在文件中。我的代码保存文件如下。我正在使用一个框架,所以数据库事务和retrevial代码可能看起来很奇怪,但值已正确设置。在存储在数据库中之前,这些文件也使用base64进行编码,因此我调用解码函数将其恢复到正常状态。
function save_file($file_id) {
$result = $DB->get_file($file_id);
$size = $result->fields['size']; //1024
$mime = $result->fields['mime']; //image/jpg
$name = $result->fields['name']; //test.jpg
header("Content-Disposition:attachment;filename=".$name);
header("Content-Type=: ".$mime);
header("Content-Length: ".$size);
base64_decode(file);
echo($file);
exit();
}
答
function save_file($file_id, $target_folder) {
$result = $DB->get_file($file_id);
$file_content = $result->fields['your_file_content_field'];
$name = $result->fields['name'];
/* Decode only if the file contents base64 encoded
* before inserting to database.
*/
$file_content = base64_decode($file_content);
return file_put_contents($target_folder.'/'.$name, $file_content);
}
答
我想你的Content-Type
头是错误的。 =
看起来像一个错字。
+1鹰眼.. – Cristian 2010-07-01 18:09:57
哈哈。搞定了! – 2010-07-01 18:11:56