1、前端上传文件html index.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 Gridfs</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="upfile" >上传图片</label>
<input type="file" id="upfile" name="upfile" />
<input type="submit" />
</form>
</body>
</html>
2、上传文件进入MongoDB数据库并返回图片的索引ID upload.php
<?php
//上传图片到
header("Content-type:text/html;charset=utf-8");
// 连接Mongo并初始化GFS
// 数据库命名 picDB;集合命名pic_userid
$conn = new MongoClient();
$db = $conn->picDB;
// 取得gridfs对象
$prefix = 'pic';
$collection = $db->getGridFS($prefix);
// 上传图片
if(isset($_FILES['upfile'])){
$id = $collection->storeUpload('upfile');
$id = strval($id);
echo "<p>图片路径为:<font color=red>http://{$_SERVER['HTTP_HOST']}/image.php?id={$id}</font></p>";
}
?>
3、根据图片ID直接从MongoDB里面获取图片资源并显示 image.php
<?php
// 根据ID索引值将图片资源取出来,即图片二进制数据
$conn = new Mongo();
$db = $conn->picDB;
// 取得gridfs对象
$prefix = 'pic';
$collection = $db->getGridFS($prefix);
$id = $_GET['id'];
$object = $collection->findOne(array('_id' => new MongoId($id)));
header('Content-type:image/jpg');
echo $object->getBytes();
?>