Skip to content

Instantly share code, notes, and snippets.

@masylum
Created December 19, 2010 17:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save masylum/747514 to your computer and use it in GitHub Desktop.
Save masylum/747514 to your computer and use it in GitHub Desktop.
Upload files directly to s3
function upload (req, res) {
var Formidable = require('formidable'),
form = new Formidable.IncomingForm();
form.encoding = 'utf-8';
form.onPart = function (part) {
if (!part.filename) {
form.handlePart(part);
} else {
(function () {
var file = {filename: part.filename, mime: part.mime, length: 0, hash: require('crypto').createHash('md5'), buffers: []};
part.on('data', function (buf) {
file.buffers.push(buf);
file.length += buf.length;
file.hash.update(buf);
});
part.on('end', function () {
form.emit('file', part.name, file);
});
}());
}
};
form.parse(req, function (err, fields, files) {
var client = require('knox').createClient(require('../config/services').s3),
buffer = new Buffer(files.file.length),
file_name = files.file.hash.digest('hex'),
length = 0;
files.file.buffers.forEach(function (buf) {
buf.copy(buffer, length, 0);
length += buf.length;
});
client.put(file_name, {
'Content-Length': buffer.length,
'Content-Type': 'text/plain'
}).end(buffer);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment