如何使用PHP在MongoDB上保存文件?

时间:2012-02-29 20:14:53

标签: php mongodb

如何在MongoDB上保存文件?
我使用PHP,它似乎不是任何信息..
另外,如果你想给我一些例子来了解如何保存和下载这些文件,我将非常感谢

1 个答案:

答案 0 :(得分:13)

查看本教程:http://learnmongo.com/posts/getting-started-with-mongodb-gridfs/

将一些代码粘贴在答案中:

<?php

// Connect to Mongo and set DB and Collection
$mongo = new Mongo();
$db = $mongo->myfiles;

// GridFS
$grid = $db->getGridFS();

// The file's location in the File System
$path = "/tmp/";

$filename = "03-smbd-menu-screen.mp3";

// Note metadata field & filename field
$storedfile = $grid->storeFile($path . $filename,
             array("metadata" => array("filename" => $filename),
             "filename" => $filename));


// Return newly stored file's Document ID
echo $storedfile;

?>

要退回文件:

<?php
// Connect to Mongo and set DB and Collection
$mongo = new Mongo();
$db = $mongo->myfiles;     

// GridFS
$gridFS = $db->getGridFS();     

// Find image to stream
$image = $gridFS->findOne("chunk-screaming.jpg");

// Stream image to browser
header('Content-type: image/jpeg');
echo $image->getBytes();

?>