Home »
Node.js
Node.js Formidable Module-3
In this article, we are going to learn about Node.js formidable module with an example of selecting, uploading and moving a file.
Submitted by Manu Jemini, on November 20, 2017
Prerequisite: Node.js Formidable Module-1, Node.js Formidable Module-2
In last two articles in of formidable, we create a form with and send it to a listener fileupload with post method after that we managed a condition on the listener and take the incoming form to parse it and write a message on the browser. Now, the task is to move or upload the file on the server with a given location and show the message that the file has been uploaded.
For this task, we need to create two variable old and a new path and we take the old path of the file by invoking files.filetoupload.path() method and use files.filetoupload.name method to get the file name.
After that, we need to call fs.rename() method by passing old and new path variable as arguments and with a callback function. Inside the callback, we write our message.
Server File
//step-1
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
//step-2
http.createServer(function (req, res) {
//step-3
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = 'C:/Users/New folder/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
//step-4
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
//step-5
}).listen(8080);
Discussing above steps:
- In the first step, we need to require all three modules.
- After that, we create a server with a callback function.
- Then, if the condition gets satisfied we take the incoming form and set the old and new path before calling the fs.rename() method.
- In else part, we create our form as usual.
Good luck.!