Tuesday, April 15, 2014

Upload file using Node.js with formidable

This example implement web app using Node.js with formidable. formidable is a node.js module for parsing form data, especially file uploads. By default, the uploaded file will be aved in /tmp directory.

To install formidable, run the command in your working directory:
$ npm install formidable

Example code, app.js (tested on Raspberry Pi and Ubuntu):
// run the command to install formidable
// $ npm install formidable
var formidable = require('formidable');
var http = require('http');
var util = require('util');
var fs = require('fs');
var os = require('os');

var app = http.createServer(
 function(req, res){
  switch(req.method){
   case 'GET':
    showPage(req, res);
    break;
   case 'POST':
    upload(req, res);
    break;
  }
 }
);
app.listen(8080);

//Display my IP
var networkInterfaces=os.networkInterfaces();

for (var interface in networkInterfaces) {
    
    networkInterfaces[interface].forEach(
        function(details){
            
            if (details.family=='IPv4' 
                && details.internal==false) {
                    console.log(interface, details.address);  
        }
    });
}

function showPage(req, res){
 fs.readFile(__dirname + '/index.html',
  function (err, data) {
   if (err) {
    res.writeHead(500);
    return res.end('Error loading index.html');
   }
  
   res.writeHead(200);
   res.end(data); 
  });
}

function upload(req, res){

 var form = new formidable.IncomingForm();
 
 form.parse(req, function(err, fields, files) {
  res.writeHead(200, {'content-type': 'text/plain'});
  res.end('File uploaded!');
  console.log("Upload completed");
  console.log(util.inspect(files));
 });
 
}

index.html
<html>
<head></head>
<body>
<h1>Upload file</h1>
<h1>Test Node.js with formidable</h1>
<div>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"><br>
<input type="submit" value="Upload">
</form>
</div>

</body>
</html>

Upload file using Node.js with formidable, tested on Raspberry Pi.

2 comments:

Anthony Young said...

How would you choose the directory to save the image to? Thanks in advance

Mauro Bucalo said...

form.uploadDir = __dirname