How would one handle a file upload with Meteor?

后端 未结 12 1482
不知归路
不知归路 2020-12-07 07:56

What would be the canonical way to handle a file upload with Meteor?

12条回答
  •  时光说笑
    2020-12-07 08:06

    Here is the best solution for this time. It uses collectionFS.

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

    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
                    }
                });
            });
        }
    });
    

    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
        }
    });
    

    Template:

    
    

提交回复
热议问题