Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active September 7, 2024 14:28
Show Gist options
  • Save joyrexus/0c6bd5135d7edeba7b87 to your computer and use it in GitHub Desktop.
Save joyrexus/0c6bd5135d7edeba7b87 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 [email protected]    \
     --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 [email protected] --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": "^17.5.4"
}
}
const fs = require('fs');
const Hapi = require('hapi');
const server = Hapi.server({
host: 'localhost',
port: Number(process.argv[2] || 8080)
});
server.route({
method: 'POST',
path: '/submit',
handler: (request, h) => {
const data = request.payload;
if (data.file) {
const name = data.file.hapi.filename;
const path = __dirname + "/uploads/" + name;
const file = fs.createWriteStream(path);
file.on('error', (err) => console.error(err));
data.file.pipe(file);
data.file.on('end', (err) => {
const ret = {
filename: data.file.hapi.filename,
headers: data.file.hapi.headers
}
return JSON.stringify(ret);
})
}
return 'ok';
},
options: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
}
}
});
const init = async () => {
await server.start();
console.log(`Server running at: ${server.info.uri}`);
};
init();
@bilalk1
Copy link

bilalk1 commented Mar 18, 2019

It is very helping!

@yogesh-xseed
Copy link

if the file size is less then 15 kb its not working

@jbarros35
Copy link

most of these old samples wont compile anymore.

@aishadeshmukh
Copy link

Thank you so much the demo. It really helped 👍

@riteshkkr
Copy link

updated code

	{
		method: "POST",
		path: "/upload",
		handler: clientController.postClientFile,
		config: {
			description: "Home",
			auth: false,
			payload: {
				maxBytes: 209715200,
				parse: true,
				allow: "multipart/form-data",
				multipart: { output: "stream" },
			},
		},
	},

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment