Skip to content

Instantly share code, notes, and snippets.

@dnprock
Created September 24, 2013 18:58
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnprock/6689567 to your computer and use it in GitHub Desktop.
Save dnprock/6689567 to your computer and use it in GitHub Desktop.
Meteor image file upload. Then send file to S3.
Template.example.events({
'change input': function(ev) {
_.each(ev.srcElement.files, function(file) {
Meteor.saveFile(file, file.name);
});
}
});
<template name="example">
<input type=file />
</template>
// original source from file upload gist
// https://gist.github.com/dariocravero/3922137
Meteor.saveFile = function(blob, name, path, type, callback) {
var fileReader = new FileReader(),
method, encoding = 'binary', type = type || 'binary';
switch (blob.type) {
case 'image/png':
case 'image/jpeg':
method = 'readAsBinaryString';
encoding = 'binary';
fileReader.onload = function(file) {
Meteor.call('saveFile', file.srcElement.result, Session.get("documentId"), path,
encoding, blob.type, callback);
}
break;
default:
method = 'readAsBinaryString';
encoding = 'binary';
break;
}
fileReader[method](blob);
}
function getS3Bucket() {
if (Meteor.absoluteUrl() === 'http://localhost:3000/') {
return 'myapp-dev';
} else if (Meteor.absoluteUrl() === 'http://myapp.meteor.com/') {
return 'myapp-staging';
} else if (Meteor.absoluteUrl() === 'http://myapp.com/') {
return 'myapp-production';
}
}
Meteor.methods({
saveFile: function(blob, name, path, encoding, type) {
var knox = Meteor.require('knox');
var client = knox.createClient({
key: '' /* S3 Key */,
secret: '' /* S3 Secret */,
bucket: getS3Bucket()
});
// from meteor async gist
// https://gist.github.com/possibilities/3443021
Future = Meteor.require('fibers/future');
var fut = new Future();
var buffer = new Buffer(blob, 'binary');
client.putBuffer(buffer, '/thumbnails/' + name, {
'Content-Length':blob.length,
'Content-Type':type,
'x-amz-acl': 'public-read'
}, function(err, res) {
fut.return(name);
});
fut.wait();
},
removeThumb: function (name) {
var knox = Meteor.require('knox');
var client = knox.createClient({
key: '' /* S3 Key */,
secret: '' /* S3 Secret */,
bucket: getS3Bucket()
});
client.deleteFile('/thumbnails/' + name, function(err, res) {
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment