Search code examples
meteorcollectionfs

Simple image uploading with collection fs


I have installed collection fs package to process my image uploads and so far,i have not uploaded a single image successfully.

I have this code in my event

'change .ip': function(event, template) {
       FS.Utility.eachFile(event, function(file) {
           var yourFile = new FS.File(file);
        SchoolImages.insert(yourFile, function (err, fileObj) {
          if (err){
             // handle error
             alert('error');

          } else {
             // handle success depending what you need to d
             alert('success');
          }
        });
     });
  }

This is my html

<input type="file" class="ip form-control" name="sn_edit" value="">

This is my collections code

SchoolImages = new FS.Collection("SchoolImages", {
    stores: [new FS.Store.FileSystem("SchoolImages", {path: "~/meteor_uploads"})]
});


if (Meteor.isServer) {
  SchoolImages.allow({
    insert: function (userId, doc) {
      return false;
    },

    update: function (userId, doc, fieldNames, modifier) {
      return false;
    },

    remove: function (userId, doc) {
      return false;
    }
  });

  SchoolImages.deny({
    insert: function (userId, doc) {
      return true;
    },

    update: function (userId, doc, fieldNames, modifier) {
      return true;
    },

    remove: function (userId, doc) {
      return true;
    }
  });
}

When i try uploading an image,no image is uploaded and no collection is created. My code gives an error alert('error') - see the code above.

How should i rectify my code to upload an image successfully?.


Solution

  • You don't have to allow db operation inside in Meteor.isServer. You can directly write the collections code as follow.


    SchoolImages = new FS.Collection("SchoolImages", {
        stores: [new FS.Store.FileSystem("SchoolImages", {path: "~/meteor_uploads"})]
    });
    
    
    
    SchoolImages.allow({
        insert: function (userId, doc) {
          return true;
        },
    
        update: function (userId, doc, fieldNames, modifier) {
          return true;
        },
    
        remove: function (userId, doc) {
          return true;
        }
      });
    

    Generally I recommend to write this code inside the lib folder when you structure your project in different folders.