1

I'm not sure if this question has ever been asked before has I've been browsing internet looking for answers about file upload and I can't find the right one. Here is the thing : I want to upload a file to the server. And this is OK. I've found a large number of discussion talking about how you can upload a file to the server.

Now my problem is I can't find a way to tell the client that the file was effectively uploaded or if there was an error... I've been trying with Meteor.call('methodName', args, function(error, result){//some code}); on the client and this on the server :

Meteor.methods({
    saveFile: function (blob, name, path, encoding) {
        var fs = __meteor_bootstrap__.require('fs');
        var path = badgesHelper.cleanPath(path);
        var name = badgesHelper.cleanName(name || 'file');
        var encoding = encoding || 'binary';
        path = Meteor.chroot + path + '/';
        console.log(path, name, encoding);

        var uploadResult = {success: false};

        fs.writeFile(path + name, blob, encoding, function (error) {
            if (error) {
                uploadResult.error = error
                Meteor.Error(500, 'An error occurred');
            } else {
                var date = new Date();
                uploadResult.success = true;
            }
        });
        return uploadResult;
    }
});

And I just can't find a way to send the uploadResult map to the client. Since the call is asynchronous, node hits the "return" before the callback function is call and that uploadResult has the real result of the function... I don't want to use filepicker.io I need to know how to do this without any package.

If I'm doing this the wrong way, please advise, as for now I'm stuck there...

Thank you

Erdal G.
  • 2,694
  • 2
  • 27
  • 37
MaxouMask
  • 985
  • 1
  • 12
  • 33

1 Answers1

0

The map is not required here since you are only returning a boolean value, you can return it directly. In case of error, you can just throw it instead of false. Also, you must throw new Meteor.Error() instead of just Meteor.Error().

The code with the changes:

Meteor.methods({
    saveFile: function (blob, name, path, encoding) {
        var fs = __meteor_bootstrap__.require('fs');
        var path = badgesHelper.cleanPath(path);
        var name = badgesHelper.cleanName(name || 'file');
        var encoding = encoding || 'binary';
        path = Meteor.chroot + path + '/';
        console.log(path, name, encoding);

        var uploadResult = false;

        fs.writeFile(path + name, blob, encoding, function (error) {
            if (error) {
                // EDIT: Throws an error
                // error.error = 500; error.reason = "An error occurred";
                throw new Meteor.Error(500, 'An error occurred');
            } else {
                // result = true
                return true;
            }
        });
    }
});
Sam
  • 7,252
  • 16
  • 46
  • 65
Prashant
  • 1,825
  • 1
  • 15
  • 18