Using Node.js for Uploading Files

|
| By Webner

Upload Files using Node.js

When we build any web application, we often need to upload some files via our application. For uploading files using Node.js, we use “Formidable” module. You can download this module or install it using npm.

Command for Installation of Formidable Module:

sudo npm install formidable

After installing it, you have to include this module in your application as:

var <variable_name> = require(‘formidable’);

The aforementioned can be done with the following steps:

A). Firstly, create the web page named as “uploadfile.js”.
B). Create the Html Form which will have input type=”file” for uploading any file.
C). Now, include the Formidable module which will parse the uploaded file. After parsing the uploaded file, it will be kept in a temporary folder of your computer.
D). You can move the uploaded file to your selected folder by using File System module(fs).
By using this following code, you can upload any file:

var httpModule = require('http');
var formidableModule = require('formidable');
var fileSystem = require('fs');
httpModule.createServer(function (request, response) {
  if (request.url == '/uploadFile') {
	var htmlForm = new formidableModule.IncomingForm();
	htmlForm.parse(request, function (err, fields, files) { 	 
  			var oldFilePath = files.filetoupload.path;  	
  	var newFilePath = '/home/webners/Documents/' + files.filetoupload.name;
  	fileSystem.rename(oldFilePath, newFilePath, function (err) {
    	if (err) throw err;
    	response.write('Your File is  uploaded and moved to new selected    path!');
    	response.end();
  	});
 });
  } else {
	response.writeHead(200, {'Content-Type': 'text/html'});
	response.write('<form action="uploadFile'" method="post" enctype="multipart/form-data">');
	response.write('<input type="file" name="filetoupload"><br>');
	response.write('<input type="submit">');
	response.write('</form>');
	return response.end();
  }
}).listen(8080);

Leave a Reply

Your email address will not be published. Required fields are marked *