How to upload file in NodeJS

As we know Node.js is a single threaded application and we can also use this to develop web applications. Sometimes, we need to integrate the HTML Forms in our web application. In the form we needs some text data, email data and file uploading. So, here we will learn how to upload file in NodeJS and also how to get form data in NodeJS.

NodeJS has an special module express. Express is a Node.js web application framework which provides some features to develop web and mobile applications.

Features of Express Framework

  • Express defines the routing for HTTP requests
  • Dynamically render HTML pages based on arguments passed in URL
  • Setup middleware for HTTP requests
  • Listening Servers for HTTP requests
  • Serving static assets like images, css, js

Express mainly works with some other modules like body-parser, multer, cookie-parser.

  • body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • multer − This is a node.js middleware for handling multipart/form-data.

Now, lets start coding…

1 : Create a project directory at any place in your computer or server.

2 : Go to the project directory and Run the commands given below one by one.

npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save

3 : Create a file express.js and paste the code given below

/*modules*/
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var fs = require('fs');
/*modules*/

app.use(express.static('assets'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({dest: '/tmp/'}).single('file'));

/*routes*/
app.get('/',function(req, res){

	res.sendFile(__dirname + '/templates/home.html');

});

app.post('/form_submit', function(req, res){

	var uploadedPath = __dirname + '/assets/uploads/' + req.file.originalname;

	fs.readFile(req.file.path, function(err,data){

		fs.writeFile(uploadedPath, data, function(err){

			if (err) {
				console.log(err);
			}else{
				response = {
					full_name: req.body.full_name,
					message: 'File Uploaded Successfully',
					filepath: uploadedPath
				};
			}

			res.end(JSON.stringify(response));
		});

	});

});
/*routes*/

/*server listening*/
var server = app.listen(8081,function(){
	var host = server.address().address;
	var port = server.address().port;
	console.log('Server listening at http://%s:%s', host, port);
});

4: Create a File home.html under templates directory in your project directory and paste the code given below

<!DOCTYPE html>
<html>
<head>
	<title>Home</title>
	<link rel="stylesheet" type="text/css" href="http://localhost:8081/css/app.css">
</head>
<body>


	<div class="container">
		<h3>Node.js Forms</h3>
		<form method="POST" action="http://localhost:8081/form_submit" enctype="multipart/form-data">
			<input type="text" name="full_name" placeholder="Full Name" />
			<input type="file" name="file" />
			<button type="submit">Submit</button>
		</form>
	</div>

</body>
</html>

5 : Create a app.css file under assets/css directory in your project directory and paste the code given below

.container{
	width: 50%;
	margin: auto;
}

.container form input, .container form button{
	height: 25px;
	display: block;
	width: 100%;
	border:solid 1px gray;
	margin: 10px;
	padding: 5px;
}

.container h3{
	text-align: center;
}

6 : Create a uploads directory in assets directory

7 : Now run the command given below and open the link in your browser http://localhost:8081

node server.js

Now test how to upload file in NodeJS 🙂

Recommended :

How to create URL in Node.js

How to use events in Node.js

Create REST API in Node.js

Upload file in Node.js

For more NodeJS Tutorials visit NodeJS page.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube.