Check it: gist: 628541 – How to save a file using MongoDB’s GridFS in Lithium- GitHub.
I just saved my first GridFS file using Lithium. I’m sure there’s a much better way of doing this outside of my controller using filters, but I’m not quite sure how those work yet.
Basically, I have two models: Job and File. The key here is to create a GridFS-aware model. In my case, it’s the File model. This is done by setting the $_meta property’s source field.
protected $_meta = array('source' => 'fs.files');
For this app’s purpose, keeping Job data separate from File data is important so I needed two save operations. First, I save my Job, then my File.
if ($this->request->data) {
if ($job->save($this->request->data)) {
$file = File::create();
$fileData = array(
'file' => $this->request->data['file'],
'job_id' => (string) $job->_id
);
if ($file->save($fileData)) {
$this->redirect('Books::index');
}
}
}
Lithium handles all the GridFS operations (as expected) from there. It knows where to look by looking specifically at the file field in your data.
What’s the result you ask? It’s a complete win, that’s what:
> db.jobs.find();
{ "_id" : ObjectId("4cb88674ad7bef7559010000"), "file" : "DeathValley02.jpeg", "first" : "Mike", "last" : "Girouard", "email" : "mikeg@migimedia.com", "key" : "blue-full", "submit_x" : "0", "submit_y" : "0", "submit" : "Upload & Preview" }
> db.fs.files.find();
{ "_id" : ObjectId("4cb88674ad7bef7559030000"), "job_id" : "4cb88674ad7bef7559010000", "chunkSize" : 262144, "length" : 18, "md5" : "c99041c6d57b58d9ae07983aec79d54d" }
Hopefully this saves someone some time. It took me all morning to get here. :)