MongoDB GridFS 存储文件功能实现方式

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();

?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值