Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: upload image file using FileReader on client and Npm.require("fs") on server

I'm having some trouble trying to upload an image file to my public/ folder using a standard <input type="file"> element.

So i have this event:

      "change .logoBusinessBig-upload":function(event, template){

            var reader = new FileReader()

            reader.addEventListener("load", function(){

                Meteor.call("saveFile", reader.result)

            })

            reader.readAsArrayBuffer(event.currentTarget.files[0])

        }

When i do a console.log(reader.result) inside the eventListeners callback, i get an ArrayBuffer object.

In my server/server.js file i have this Meteor.method:

        saveFile:function(file){

            var fs = Npm.require("fs")

            fs.writeFile('message.jpg', file, function (err) {

                console.log("file saved")

            });

        }

However, the file doesn't get saved and the console never says "file saved". What am i doing wrong here?

like image 270
kevinius Avatar asked Mar 17 '23 22:03

kevinius


1 Answers

Try this

//client.js

'change .logoBusinessBig-upload': function(event, template) {

    var file = event.target.files[0]; //assuming you have only 1 file
    if (!file) return;

    var reader = new FileReader(); //create a reader according to HTML5 File API

    reader.onload = function(event){          
      var buffer = new Uint8Array(reader.result) // convert to binary
      Meteor.call('saveFile',buffer);
    }

    reader.readAsArrayBuffer(file); //read the file as arraybuffer
}

//server.js

'saveFile': function(buffer){
    var fs = Npm.require("fs");
    fs.writeFile('/location',new Buffer(buffer),function(error){...});

}

Explanation

You read the file as ArrayBuffer, but current DDP can't send it, so you 'convert' it to Uint8Array, then Meteor.call

On the server, then you have to convert it by calling new Buffer(buffer) to save it. The '/location' can't be in meteor folder as this will trigger a reload, maybe save it to some TmpDir

like image 115
Green Avatar answered Apr 06 '23 02:04

Green