【发布时间】:2010-11-06 01:28:18
【问题描述】:
我知道你们中的一些人会说这不是正确的方法,但我在紧迫的期限内完成申请,到目前为止我无法返回并修改代码以将图像存储在目录中。
现在已经清除了
我的问题是我通过键入此内容将图像插入到数据库中。
(不要介意类安全调用,所做的只是检查数据是否有效)
$filename = $security->secure($_FILES['imgschool']['name']);
$tmpname = $security->secure($_FILES['imgschool']['tmp_name']);
$imgsize = $security->secure($_FILES['imgschool']['size']);
$imgtype = $security->secure($_FILES['imgschool']['type']);
$school = $security->secure($_POST['school']);
//begin upload
if($imgsize > 0) {
$handle = fopen($tmpname, "r");
$content = fread($handle, filesize($tmpname));
$content = addslashes($content);
//code to add all this to database
}
变量 $content 是图像,它得到的只是附加斜线。我记得有人曾经提到过用一种叫做 base64 的东西来做这件事,但我几乎记不起它是怎么写的了。
这就是我从数据库中调用图像的方式
除了所有的查询等等 这是调用图像的主要部分
header("Content-length: ".$imgsize);
header("Content-type: ".$imgtype);
header("Content-Disposition: attachment; filename=".$imgname);
print $row['img'];
我遇到的问题是,而不是显示的图像。网址只显示,所以在这种情况下我只看到这个
http://localhost/admin/school-catalog.php?page=gallery&id=4
当打开页面查看带有正确参数设置的图像时。
对于那些想要查看正在执行的查询以保存图像等的人 我复制了整个部分
//save image to db
if(isset($_POST['btnupload'])) {
$filename = $security->secure($_FILES['imgschool']['name']);
$tmpname = $security->secure($_FILES['imgschool']['tmp_name']);
$imgsize = $security->secure($_FILES['imgschool']['size']);
$imgtype = $security->secure($_FILES['imgschool']['type']);
$school = $security->secure($_POST['school']);
//begin upload
if($imgsize > 0) {
$handle = fopen($tmpname, "r");
$content = fread($handle, filesize($tmpname));
$content = base64_encode($content);
}
$save = mysql_query("insert into tbl_schoolgallery(id,hash,img,imgtype,imgsize) values(null,'$school','$content','$imgtype','$imgsize')") or die(mysql_error());
header("Location: school-catalog.php?page=school_gallery");
}
//call image from db
$query = mysql_query("select * from $tbl where id = '$id'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)) {
$imgtypeget = explode("/", $row['imgtype']);
$imgname = "img.".$imgtypeget[1];
$imgtype = $row['imgtype'];
$imgsize = $row['imgsize'];
header("Content-length: ".$imgsize);
header("Content-type: ".$imgtype);
print base64_decode($row['img']);
print $row['img'];
}
【问题讨论】:
-
你不应该使用 print $content 吗?
-
我不能,因为我从数据库调用图像
-
那部分代码和一个数据样本丢失了,你确定img列包含正确的值吗?
-
Content-Disposition 用于设置下载的文件名(例如,如果您正在向用户发送 Word 文档并在他们的 Save As... 提示出现时想要一个默认值)。如果在这种情况下正确使用,它将使其直接转到图像 URL 将强制下载而不是显示。
-
虽然在 SQL 数据库中存储二进制数据存在问题,但如果您关心事务(尝试将文件系统与 sql 后端同步)、可伸缩性(大量工具可以帮助RDMS)、备份(为什么要编写/使用另一个备份系统?),以及尤其是所有这些问题的相互作用。