TrinityTuts

Upload image in node.js express

Last updated on July 31st, 2016 at 11:13 am

Node is very powerful and light weight server for web application and its speed is also very fast as compare to PHP server. In this post i am going to explain you how to upload image in node.js express. Express is most useful framework for node for web application most of node based web application use Express. This is very easy to understand please follow steps to upload your image.

Step 1. Before you start you need to install formidable module using npm from official site formidable. Run command on your prompt

npm install formidable@latest

Step 2. Create your image upload form inside your expressApp > views > imageUpload.jade. Make sure add this file in your routes.

include layout
    div.container
        h2 Image Upload Form
        form#fileUpload(method="post" action="/upload" enctype="multipart/form-data") 
            label(for="payload") Select a file to upload:     
            input#payload(type="file" name="myFile" accept="image/*") 
            br 
            button#upload Upload

Step 3. Now final step where we handle upload image. In below code we can handle image upload

var express = require('express');
var router = express.Router();
var util = require("util"); 
var fs = require("fs");
var formidable = require('formidable');
var path = require('path');

/* GET home page. */

router.get('/imageUpload', function(req, res, next){
    res.render('imageUpload', { title: 'Image upload form' });
});

router.post("/upload", function(req, res, next){ 
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        // `file` is the name of the <input> field of type `file`
        console.log(files);
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));
    });
    form.on('error', function(err) {
        console.error(err);
    });
    form.on('progress', function(bytesReceived, bytesExpected) {
        var percent_complete = (bytesReceived / bytesExpected) * 100;
        console.log(percent_complete.toFixed(2));
    });
    form.on('end', function(fields, files) {
        /* Temporary location of our uploaded file */
        var temp_path = this.openedFiles[0].path;
        /* The file name of the uploaded file */
        var file_name = this.openedFiles[0].name;
        /* Location where we want to copy the uploaded file */
        var new_location = 'F:/node/expressApp/myAppExpress/public/images/';

        fs.readFile(temp_path, function(err, data) {
            fs.writeFile(new_location + file_name, data, function(err) {
                fs.unlink(temp_path, function(err) {
                    if (err) {
                        console.error(err);
                        } else {
                        console.log("success!");
                    }
                });
            });
        });
    });
});
module.exports = router;

You also add some extra thing in it like show progress, error etc. This is simple and easy way to upload image upload.

🙂