Search code examples
javascriptmongodbmeteorcollectionfs

How to insert an image in CollectionFS?


I'm trying to create a collection of images using the CollectionFS in meteor. I used the following code from https://github.com/CollectionFS/Meteor-CollectionFS/wiki/Insert-One-File-From-a-Remote-URL

        var url='data/2.jpg';
        var newFile = new FS.File();
        newFile.attachData(url, function (error) {
            if (error) throw error;
            newFile.name("testImage.jpg");
            Images.insert(newFile, function (error, fileObj) {});
        });        

The above code is written in the startup function in the 'js/server.js' file & the image it is referring to is 'js/data/2.jpg'.

But it doesn't seem to work & throws the this error:

Error: ENOENT, stat 'C:\Users\[username]\WebstormProjects\test\.meteor\local\build\programs\server\data\2.jpg'

Solution

  • The error ENOENT is an abbreviation for “Error NO ENTry“. You receive this error because the file 2.jpg cannot be accessed or does not exist in the directory C:\Users\[username]\WebstormProjects\test\.meteor\local\build\programs\server\data\.

    If you want to insert a file from a remote URL, you need to supply an accessible URL, for example:

    Images = new FS.Collection("images", {
        stores: [new FS.Store.FileSystem("images", {path: "~/uploads"})]
    });
    
    if (Meteor.isServer) {
        Meteor.startup(function () {
            var url = 'http://www.panderson.me/images/lena.jpg';
            var newFile = new FS.File();
            newFile.attachData(url, function (error) {
                if (error) throw error;
                newFile.name("lena.jpg");
                Images.insert(newFile, function (error, fileObj) {
                    console.log(error);
                    console.log(fileObj);
                });
            });
        });
    }
    

    I assume that you don't want to insert a file from a remote URL. If this is the case, place your file in the private directory and change the variable url to: "assets/app/lena.jpg".

    Images = new FS.Collection("images", {
        stores: [new FS.Store.FileSystem("images", {path: "~/uploads"})]
    });
    
    if (Meteor.isServer) {
        Meteor.startup(function () {
            var url = "assets/app/lena.jpg";
            var newFile = new FS.File();
            newFile.attachData(url, function (error) {
                if (error) throw error;
                newFile.name("lena.jpg");
                Images.insert(newFile, function (error, fileObj) {
                    console.log(error);
                    console.log(fileObj);
                });
            });
        });
    }