Async upload help


#1

Morning all,

I’m trying to add my own simple file-upload mechanism. (The reason I’m not using any of the fancy upload packages is that they’re too much overkill and I don’t need to store anything in a collection)

So what I’ve got is a simple form with a multiple-file input control like this:

<div class="form-group">
            <label>Files to upload</label>
            <input class="form-control" id="newFiles" name="newFiles" type="file" multiple="true">
</div>

and a client-side event:

Template.addItem.events({
    'submit form': function submitForm(event) {
        event.preventDefault();
        var files = event.target.newFiles.files;
        for (var i = 0, f; f = files[i]; i++) {
            var reader = new FileReader();
            reader.onload = function (f) {
                return function (e) {
                    console.log(f.name);
                    Meteor.call('file-upload', f.name, e.target.result);
                };
            }(f);
            reader.readAsBinaryString(f);
        }
    }
});

And finally the server-side method:

Meteor.methods({
    'file-upload': function(fileName, fileData) {
        var my_fs = Npm.require('fs');
        console.log(fileName);
        my_fs.writeFile(fileName, new Buffer(fileData, 'binary'));
    }
});

This works! Hurrah! However…

I’d like to do something (like showing ‘upload complete’ or executing some code to copy the uploaded files to another spot on the server) but I have no idea how to get this done. I know it’s something to do with the async nature of Meteor/NodeJS, but I’ve not yet hit the sweet spot of underdtanding this.

Any help would be appreciated.