What would be the canonical way to handle a file upload with Meteor?
html file through a browser, the client will be able to upload a file to the server using Ajax and pure JavaScript. A pure JavaScript file uploader simplifies Ajax based interactions with the server.
I used http://filepicker.io. They'll upload the file, store it into your S3, and return you a URL where the file is. Then I just plop the url into a DB.
Wget the filepicker script into your client folder.
wget https://api.filepicker.io/v0/filepicker.js
Insert a filepicker input tag
<input type="filepicker" id="attachment">
In the startup, initialize it:
Meteor.startup( function() {
filepicker.setKey("YOUR FILEPICKER API KEY");
filepicker.constructWidget(document.getElementById('attachment'));
});
Attach a event handler
Templates.template.events({
'change #attachment': function(evt){
console.log(evt.files);
}
});
For images, I use a method similar to Dario's except I don't write the file to disk. I store the data directly in the database as a field on the model. This works for me because I only need to support browsers that support the HTML5 File API. And I only need simple image support.
Template.myForm.events({
'submit form': function(e, template) {
e.preventDefault();
var file = template.find('input type=["file"]').files[0];
var reader = new FileReader();
reader.onload = function(e) {
// Add it to your model
model.update(id, { $set: { src: e.target.result }});
// Update an image on the page with the data
$(template.find('img')).attr('src', e.target.result);
}
reader.readAsDataURL(file);
}
});
I've just come up with an implementation of file uploads using Meteor.methods and HTML5 File's API. Let me know what you think.
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