Skip to content

Instantly share code, notes, and snippets.

@petreboy14
Created July 3, 2014 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petreboy14/1de007355112ae280a8f to your computer and use it in GitHub Desktop.
Save petreboy14/1de007355112ae280a8f to your computer and use it in GitHub Desktop.
var concat = require('concat-stream');
var Hapi = require('hapi');
var multiparty = require('multiparty');
var request = require('request');
var server = new Hapi.server('localhost', 9000);
function createMedia(request, reply) {
var params = {};
var form = new multiparty.Form();
// This function is more of a check to see if you've gotten each part stream (files and fields).
// If everything has been processed then do something with the file stream
function finishParsing() {
for (var param in params) {
if (!params[param]) return; // We're still missing a param so don't finish yet
}
// Do fancy stuff
// Prepare form for sending to other server
var r = request.post('http://<other-super-server>', function (err, res, body) {
if (err) {
// handle error
} else {
// handle non error
}
});
var f = r.form();
// When you don't let hapi parse the form filename and content type headers are directly on the file rather then
// in file.hapi.
f.append('file', params.file, { filename: params.file.filename, contentType: params.file.headers['content-type']});
// Append other fields that you want
}
form.parse(request.payload);
form.addListener('part', function (part) {
if (part.name === 'file') { // This would be whatever the 'file' stream name is
params.file = part; // The part is actually a stream so you'd handle that differently than just fields
finishParsing(); // You don't have to wait for the actual stream to buffer when you dont parse it.
} else {
params[part.name] = false; // This handles any fields that are sent
part.pipe(concat({ encoding: 'string', function (data) { // Even the fields are streams so we have to buffer them up to get their values
params[part.name] = data;
finishParsing(); // Done processing this field so maybe we're done
}));
}
});
}
server.route({
method: 'POST',
path: '/media',
handler: createMedia,
config: {
output: 'stream', // Still want stream objects
parse: false, // We don't want Hapi to actually parse the mutltipart stuff and buffer it
maxBytes: 5368709120
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment