Home » Node.js

Node.js Formidable Module-2

In this article, we are going to learn about Node.js formidable module with an example of selecting a file and submitting to server. Here, we will understand how file is uploaded to the server?
Submitted by Manu Jemini, on November 20, 2017

Prerequisite: Node.js Formidable Module-1

As we already show our form in the previous article, in this article we were going to show a response on browser about our file uploadation while taking the control on form action fileupload, for which we are going to use our first method. IncomingForm() by which we create an incoming form and parse it with a request and invoke a function with fields of the file and the files.

Server File

var http = require('http');
var formidable = require('formidable');
http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
      res.write('File uploaded');
  } 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">');
    return res.end();

Note: The most important and noticeable step is step-5, where we were using .IncomingForm() method and then parse the form.

Discussion of above steps:

  • First, we need to http and formidable module and store their reference in a local variable.
  • After that, we create http server by using .createServer() method.
  • Then we check the condition on listener fileupload.
  • If the condition satisfied, we take the incoming form in a local variable form and parse it. Then we write our message on the browser screen.
  • In else part, we create a form with post method and fileupload listener.
formidable module 1 example

formidable module 2 example

Next: Node.js Formidable Module-3

Good day!

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.