Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: ArrayBuffer (FileReader result) is not passed to Meteor.method()

I have this event (upload of an image file using <input type="file">):

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

            var reader = new FileReader()

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

                var x = reader.result

                console.log(x)

                Meteor.call("saveFile", x)

            })

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

        }

and this Meteor.method()

       saveFile:function(file){

            console.log(file)

            var fs = Npm.require("fs")

            fs.writeFile('../../../../../public/jow.txt', file, function (err) {


                console.log("file saved")

            });

        }

The console.log(x) in the event outputs an ArrayBuffer object, while the console.log(file) in the Meteor.method() shows and empty {} object.

Why is that? The ArrayBuffer should have been passed to the Meteor.method()

like image 809
kevinius Avatar asked Dec 20 '22 09:12

kevinius


2 Answers

//client.js

'change': function(event, template) {
    event.preventDefault();
    var file = event.target.files[0]; //assuming you have only 1 file
    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){
    fs.writeFile('/location',new Buffer(buffer),function(error){...});
}

You can't save to /public folder, this triggers a reload

like image 195
Green Avatar answered Feb 09 '23 01:02

Green


Client-server communication via methods in Meteor uses the DDP protocol, which only supports EJSON-able data-types and does not allow the transmission of more complex object like your ArrayBuffer, which is why you don't see it on the server.

I suggest you read the file as a binary string, send it to your method like that and then manipulate it (either via an ArrayBuffer or by some other means) once it's on the server.

like image 38
richsilv Avatar answered Feb 08 '23 23:02

richsilv