Skip to content

Instantly share code, notes, and snippets.

@dogrocker
Forked from joyrexus/README.md
Created June 7, 2016 07:04
Show Gist options
  • Save dogrocker/fe9c8874a7f4cbff138f0c438bcad306 to your computer and use it in GitHub Desktop.
Save dogrocker/fe9c8874a7f4cbff138f0c438bcad306 to your computer and use it in GitHub Desktop.
Form/file uploads with hapi.js

Demo of multipart form/file uploading with hapi.js.

Usage

npm install
npm run setup
npm run server

Then ...

npm run test

... or try:

curl --form file=@data.csv    \
     --form firstName=Melvin  \
     --form lastName=Mooney   \
     http://localhost:8080/submit

See also

Other multipart/form-data demos:

A B C
a b c
1 2 3
{
"name": "file-upload-demo",
"version": "0.0.0",
"description": "multipart form/file upload demo with hapi.js",
"main": "server.js",
"scripts": {
"setup": "[ -d uploads ] || mkdir uploads",
"test": "curl --form file=@data.csv --form user=Jones http://localhost:8080/submit",
"server": "node server.js"
},
"keywords": [
"multipart",
"upload",
"file",
"form",
"hapi",
"demo"
],
"author": "J. Voigt",
"license": "BSD-2-Clause",
"dependencies": {
"hapi": "~6.8.0"
}
}
var fs = require('fs');
var Hapi = require('hapi');
var server = Hapi.createServer('localhost', Number(process.argv[2] || 8080));
server.route({
method: 'POST',
path: '/submit',
config: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
},
handler: function (request, reply) {
var data = request.payload;
if (data.file) {
var name = data.file.hapi.filename;
var path = __dirname + "/uploads/" + name;
var file = fs.createWriteStream(path);
file.on('error', function (err) {
console.error(err)
});
data.file.pipe(file);
data.file.on('end', function (err) {
var ret = {
filename: data.file.hapi.filename,
headers: data.file.hapi.headers
}
reply(JSON.stringify(ret));
})
}
}
}
});
server.start(function () {
console.log('info', 'Server running at: ' + server.info.uri);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment