五、GridFS
5.1 基本操作
实例代码:
==Gridfa.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mongo GFS存储上传文件</title>
</head>
<body>
<form action="dealGFS.php" name="form1" method="post" enctype="multipart/form-data">
<input type="file" name="upfile" />
<input type="submit" value="上传" />
</form>
</body>
</html>
==dealGFS.php
<?php
try {
$conn = new Mongo();
$db = $conn->selectDB("dbtest");
//初始化GridFS
$grid = $db->getGridFS();
$name = $_FILES['upfile']['name'];
//print_r($_FILES['upfile']);
//保存文件
$id = $grid->storeUpload('upfile', $name);
$type= "";
$ext = end(explode('.', $name));
switch ($ext) {
case "jpg": $type = "image/jpeg"; break;
case "gif": $type = "image/gif"; break;
case "png": $type = "image/png"; break;
case "txt": $type = "text/plain"; break;
case "pdf": $type = "application/pdf"; break;
case "zip": $type = "application/x-zip"; break;
}
//更新文件信息
$files = $db->fs->files;
$files->update(array("filename" => $name), array('$set' => array("contentType" => $type, "aliases" => null, "metadata" => null)));
//显示列表
$cursor = $grid->find();
foreach ($cursor as $obj) {
?>
<img src="getFile.php?filename=<?php echo $obj->getFilename(); ?>" width="150" />
<?php
}
$conn->close();
echo "<a href='gfs.html' target='_self'>返回继续上传</a>";
} catch(Exception $e) {
echo $e->message();
}
?>
==getFile.php
<?php
$conn = new Mongo();
$db = $conn->dbtest;
$filename = $_GET['filename'];
// GridFS
$gridFS = $db->getGridFS();
$image = $gridFS->findOne(array('filename'=>$filename));
//设定文档类型,显示图片
header('Content-type: image/jpeg');
echo $image->getBytes();
?>