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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With