How would you access a folder full of images, get the url for each image and put it in an array, then {{each}} over that array to display each image on a page of my choosing? Everyone keeps saying CollectionFS, but for some reason, when I set it up:
var imageStore = new FS.Store.FileSystem('images', {
path: '~/category/engagements'
});
Images = new FS.Collection('images', {
stores: [imageStore]
});
I can access Images in the console, but the array is empty. Isn't this all I need to do?
CollectionFS keeps a mongo collection that essentially points to images that have been stored in a file system somewhere, either on the server's disk or in the cloud. afaik, you can't simply point CollectionFS at a directory full of files, you need to put the files there using CollectionFS in the first place with (in your case) Images.insert()
I've found your question very interesting so I've started to think about a way. I'm pretty new to Meteor and Node.js so I imagine that someone with much better understanding can come up with a better solution but my basic idea is to import every image from a directory to a CollectionFS.
Here is what I came up with (beware, this is a 10 minute mock-up not a copy-paste solution!)
var basedir = '../../../../../public/';
var imageStore = new FS.Store.FileSystem("images", {
path: basedir
});
Images = new FS.Collection("images", {
stores: [imageStore]
});
if (Meteor.isServer) {
Images.allow({
'insert': function () {
return true;
},
'download' : function(){
return true;
}
});
function importFiles(importDir) {
var dir = basedir + importDir;
var files = fs.readdirSync(dir);
_(files).each(function(f){
fs.readFile(dir + f, Meteor.bindEnvironment(function (err, data) {
if (err) throw err;
var newFile = new FS.File();
newFile.attachData(data, {type: 'image/png'});
newFile.name(f);
var insertedFile = Images.insert(newFile,function(err,fob){
if (err) throw err;
console.log('Uploaded successfully');
});
}));
})
}
importFiles('import/'); // this dir in under my public folder
}
This code imports everything from public/import to the directory specified for the imageStore
.
Be careful though, this can cause serious memory issues because it's reading the whole file with fs.readFile
You need to install the Node.js fs library meteor add peerlibrary:fs
Don't forget to filter the file list and set the correct MIME type based on the extension for example.
After you have imported the images you can use CollectionFS find()`` to list the images and then
fileObject.url()``` to display them.
There are examples on CollectionFS GitHub page e.g.:
https://github.com/CollectionFS/Meteor-CollectionFS/#url