我正在尝试使用GridFS将图像保存到MondoDB集合。为了测试这个,我做了以下几点:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
// open connection
$m = new MongoClient();
$db = $m->selectDB('ImageDatabase');
$gridUploads = $db->getGridFS('images');
// save image
$fileName = 'C:\Users\Thomas\Pictures\commits.png';
$gridUploads->storeFile($fileName);
// load image
$doc = $gridUploads->findOne($fileName);
// dsplay image
header('Content-type: image/png');
echo $doc->getBytes();
?>
</body>
</html>
这应该将图像上传到集合中,然后从集合中获取相同的图像并显示它。
此后的收集内容为:
{
"_id" : ObjectId("52a6fcdd1dc38f0c3c0016bf"),
"filename" : "C:\\Users\\Thomas\\Pictures\\commits.png",
"uploadDate" : ISODate("2013-12-10T11:37:01.000Z"),
"length" : 179952,
"chunkSize" : 262144,
"md5" : "768d618923442668ca2a60f02be59d52"
}
的print_r($ DOC):
MongoGridFSFile Object
(
[file] => Array
(
[_id] => MongoId Object
(
[$id] => 52a6fcdd1dc38f0c3c0016bf
)
[filename] => C:\Users\Thomas\Pictures\commits.png
[uploadDate] => MongoDate Object
(
[sec] => 1386675421
[usec] => 0
)
[length] => 179952
[chunkSize] => 262144
[md5] => 768d618923442668ca2a60f02be59d52
)
[gridfs:protected] => MongoGridFS Object
(
[w] => 1
[wtimeout] => 10000
[chunks] => MongoCollection Object
(
[w] => 1
[wtimeout] => 10000
)
[filesName:protected] => images.files
[chunksName:protected] => images.chunks
)
[flags] => 0
)
然而,结果的正文内容是:
<img style="-webkit-user-select: none" src="http://localhost/path-to/the-script.php">
任何想法为什么?
谢谢!
答案 0 :(得分:0)
基于您的第一个代码示例(混合HTML和PHP),您将在HTML本身内回显图像的字节。在发送响应主体之后还有调用header()
的问题(header()
PHP docs中讨论的第一件事之一)。我假设您的意思是拥有一个<img>
标记,其src
属性指向一个单独的PHP脚本,该脚本只需设置Content-type
标头并返回图像字节。
如果你真的想在页面响应中输出图像字节,你应该考虑使用数据URI:
但是,将src
属性指向PHP脚本可能是更好的选择(特别是对于大图像)。我无法解释原始脚本是如何生成的:
<img style="-webkit-user-select: none" src="http://localhost/path-to/the-script.php">
......但这肯定是你应该在这里瞄准的目标。
关于MongoGridFSFile::getBytes()
的使用,您应该注意getResource()
会更有效,尤其是对于大型图片。使用该资源可以通过一次只在内存中加载两个块(来自GridFS)来减少内存消耗。可以找到使用getResource()
输出文件内容的简明示例here。