//start client.js
Template.upload.events({
//call upload function when the file-input element changes
'change #file-input': function(event){
upload_function(event);
},
});
//upload funtion
upload_function = function (event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(fileLoadEvent) {
//call created upload method and pass file name, and file-reader info
Meteor.call('upload', file.name, reader.result,function(error, result) {
console.log(result)
});
};
reader.readAsBinaryString(file);
}
//end client.js
//start server.js
import fs from 'fs';
Meteor.methods({
'upload': function(fileinfo, filedata) {
//get user info based on current logged in user
var user_info = Meteor.users.findOne({"_id": this.userId}, {fields: {"_id": 1}});
if(!user_info){
return "Nope, not happening";
}
//path can be any directory you like, I decided to upload to public
/*if you want to create directories on the fly,
you'll need to add some extra code, its really easy.*/
var path = process.env['METEOR_SHELL_DIR'] + '/../../../public/';
//add user id to file name and move
fs.writeFile(path+user_info._id+fileinfo, filedata, {encoding: 'binary'});
},
});
//end server.js
//template stuff
<head>
<title>upload</title>
</head>
<body>
{{> loginButtons}}
{{> upload}}
</body>
<template name="upload">
<input id="file-input" class="form-control" type="file">
</template>
I was passing the UserID in the functioncall initially, which is really insecure, that’s why the old bit was not working (I just found the old code).
Now we just check on the server to find the current user, without any client input.
You can add other code to check !user or what not, let me know if you need more help.
The page will reload for everyone because a dir changed, so you can move it to some external dir/service instead (like cloudinary)