Thursday, 29 June 2017

How to upload file/images using nodejs?

How to upload file using nodejs?

I am assuming you already have install NodeJS in your System, Just follow below simple steps


Install below module ?
npm install express
npm install fs
npm install body-parser
npm install multer



HTML Part?
Create a file upload.html and add below code in file.

        <form action="http://127.0.0.1:8081/file_upload" enctype="multipart/form-data" id="uploadForm" method="POST" onsubmit="return uploadForm()">
Upload File: <input name="file" size="50" type="file" />
            <br />
<input type="submit" value="Upload File" />
        </form>




Node JS Code create upload.js file and add below code.
var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer  = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({ dest: './tmp' });

app.get('/upload.html', function (req, res) {
   res.sendFile( __dirname + "/" + "upload.html" );
})

app.post('/file_upload', upload.single('file'), function (req, res) {
    console.log(req.file);
    
    
   var file = __dirname + "/public/upload/" + req.file.originalname;
   
   
   fs.readFile( req.file.path, function (err, data) {
      fs.writeFile(file, data, function (err) {
         if( err ){
            console.log( err );
            }else{
               response = {
                  message:'File uploaded successfully',
                  filename:req.file.originalname
               };
            }
         console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   
   console.log("Example app listening at http://%s:%s", host, port)
})



Question: Following are sample of file object in ?
 { fieldname: 'file',
  originalname: 'Desert.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './tmp',
  filename: '3570feafa527690b90b972a1bf085bdd',
  path: 'tmp\\3570feafa527690b90b972a1bf085bdd',
  size: 845941 }


Create following empty folder?
/tmp
/public
/public\upload



Now Start the Node project?
node upload.js



Access the Web URL?
http://127.0.0.1:8081/upload.html



Select the File and click on Upload File?
It will show below simiar message
{"message":"File uploaded successfully","filename":"Desert.jpg"}
Question: What port we have used here?
We have used 8081 port, but you can change it by change in upload.js