meteor File Uploading CollectionFS

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

However, if you're really serious about storage, and you want to store millions of images, you're going to need to leverage Mongo's GridFS infrastructure, and create yourself a storage layer. For that, you're going to need the excellent CollectionFS subsystem.

Start by adding the necessary packages.

meteor add cfs:standard-packages
meteor add cfs:filesystem

And adding a file upload element to your object model.

<template name="yourTemplate">
    <input class="your-upload-class" type="file">
</template>

Then add an event controller on the client.

Template.yourTemplate.events({
    'change .your-upload-class': function(event, template) {
        FS.Utility.eachFile(event, function(file) {
            var yourFile = new FS.File(file);
            yourFile.creatorId = Meteor.userId(); // add custom data
            YourFileCollection.insert(yourFile, function (err, fileObj) {
                if (!err) {
                   // do callback stuff
                }
            });
        });
    }
});

And define your collections on your server:

YourFileCollection = new FS.Collection("yourFileCollection", {
    stores: [new FS.Store.FileSystem("yourFileCollection", {path: "~/meteor_uploads"})]
});
YourFileCollection.allow({
    insert: function (userId, doc) {
        return !!userId;
    },
    update: function (userId, doc) {
        return doc.creatorId == userId
    },
    download: function (userId, doc) {
        return doc.creatorId == userId
    }
});

Thanks to Raz for this excellent example. You'll want to check out the complete CollectionFS Documentation for more details on what all CollectionFS can do.



Got any meteor Question?