Reputation: 17166
I am trying to insert a bunch of pdf-files into MongoDB using GridFS, but get a MongoGridFSException
with the message: error setting up file name in path, where name is the absolute path to the pdf-document on the file system.
I'm using a very simple CLI-script:
$it = new DirectoryIterator(__DIR__ .'/files');
while ($it as $file) {
$grid->storeFile($file->getPathname(), array('metadata' => $metadata));
}
I find the lack of documentation for GridFS disturbing. The examples in MongoGridFS and storeFile() all just show a simple filename as first argument; if the data is retrieved from this filename, what basePath does the script assume (cwd
, __DIR__
or something completely different?) or can I just add the absolute path (judging from the error message, probably not)?
I was contemplating on using storeBytes(file_get_contents($file->getPathname())
instead, but then how do I retrieve the file, when there is no filename associated with it? Do I add the filename in the 2nd argument (options-array)?
Also, if I want to know the mine/type of a stored file, do I have to specify it in the metadata manually or is this determined automatically when inserting the file?
TL;DR: I have no idea how to work with GridFS and the php-docs are of poor quality. Can at the very least, someone point out better examples/documentation?
Upvotes: 1
Views: 3236
Reputation: 1566
I use the full path to the file when I call $grid->storeFile(). Also, yes, I store the mime type in the metadata. So, my call looks like this:
$id = $grid->storeFile($uploaded_file,
array(
'ownerNodeUuid' => $additional['nodeUuid'],
'ownerField' => $additional['fieldUuid'],
'originalFilename' => $name,
'type' => $type,
'size' => $size
),
array(
'safe' => 1
));
and this creates an entry like this:
db.myPrefix.files.findOne();
{
"_id" : ObjectId("4ea1912af3e145731c000010"),
"ownerNodeUuid" : "74DAB098-4A6F-4172-84AB-EDAFAA9FE22D",
"ownerField" : "C58AD24C-7A8C-402A-BE82-2D315BC5F7C0",
"originalFilename" : "image001.png",
"type" : "image/png",
"size" : 73679,
"filename" : "/tmp/phpNhAmGK",
"uploadDate" : "Fri Oct 21 2011 16:35:06 GMT+0100 (BST)",
"length" : 73679,
"chunkSize" : 262144,
"md5" : "3e36620fdfebdf9fbf311e996a4bc46c"
}
, so in this case $uploaded_file = "/tmp/phpNhAmGK";
Hope that helps. There are plenty of examples around on the web, but I agree that the PHP library documentation is sometimes a bit sparse... It's best to think about it as a simple wrapper around the MongoDB shell functions, so the first place I look is always the MongoDB site itself, and then when I understand what something is supposed to do in MongoDB, I look for the PHP documentation for the PHP version of that functionality.
Upvotes: 3