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

//step-1
var http = require('http');
//step-2
var formidable = require('formidable');
//step-3
http.createServer(function (req, res) {
//step-4
  if (req.url == '/fileupload') {
//step-5
    var form = new formidable.IncomingForm();
    
form.parse(req, function (err, fields, files) {
      res.write('File uploaded');
      res.end();
    });
  } else {
//step-6
    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();
  }
}).listen(8080);

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.