Skip to content

Instantly share code, notes, and snippets.

@shamsher31
Last active August 29, 2015 14:17
Show Gist options
  • Save shamsher31/e0a2b8432f5fe0f5771d to your computer and use it in GitHub Desktop.
Save shamsher31/e0a2b8432f5fe0f5771d to your computer and use it in GitHub Desktop.
Hapi-file-upload
// http://www.cronj.com/blog/hapi-file-upload-download/
var hapi = require('hapi');
var fs = require('fs');
// Create a server with a host and port
var server = new hapi.Server();
server.connection({
host: '127.0.0.1',
port: 8000
});
// Add the route
server.route({
method: 'GET',
path:'/',
handler: function (request, reply) {
reply(
'<form action="/upload" method="post" enctype="multipart/form-data">' +
'<input type="file" name="fileUpload">' +
'<input type="submit" value="Upload">' +
'</form>'
);
}
});
server.route({
path: '/upload',
method: 'POST',
config: {
payload: {
maxBytes: 1048576, // 1MB
output: 'stream',
allow: 'multipart/form-data',
parse: true
},
handler: function (request, reply) {
// This is the directory you wish to place the files.
var uploadDir = './uploads/';
// Create stream where the files will go.
var writeStream = fs.createWriteStream(uploadDir + request.payload.fileUpload.hapi.filename);
// Pipe the payload file into the write stream.
request.payload.fileUpload.pipe(writeStream);
// On stream end or error send a response.
request.payload.fileUpload.on('end', function(){
reply({"Status":"Done"});
}).on('error', function(){
reply('Error in uploading');
});
}
}
});
// Start the server
server.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment