How to upload image to nodejs and expressjs server using javascript

In web application development, most of the time you need to upload, save images and other files like pdf, docs etc. So in this blog, I will show you two ways to upload images to nodeJs server and ExpressJs server using Javascript. One is using “Sending image data as base64 string to server” and other is to “send as multipart/form-data“.

Sending images or files as a base64 string to nodeJs backend.

In this method, I will convert images to a base64 string and send that server inside the request body in the post request.

I will use FileReader to read the files and store as a base64 string.
Consider you have input type file

<input type="file" id="myFile">

Test Cases For Node js + Mocha – Beginner Guide

You can get file after selecting the image as

let file = document.getElementById("myFile").files[0];

If you are working with AngularJs and ReactJs, you can use the onChange event and get the event when a file is selected. e.g.

<input type="file" id="myFile" onChange={this.handleFile}>   //reactJs
<input type="file" (change)="handleFile($event)" />  //Angular

function handleFile(event) {
    let file = event.target.files[0];
}

More about MEAN Stack you want to know!

After getting the file from input, you can convert it to base64 string using below function. You will get the file in the callback function.

function readFile(file, cb) {
    let myReader = new FileReader();
    myReader.onloadend = function (e) {
        cb(myReader.result);
    };
    myReader.readAsDataURL(file);
};

let callback function as

function cb(base64string) {
    /*do next steps here like sending image base64string to the server.*/
}

Focusing Your Design Efforts for Maximum Leverage in 2015 – Part 3

OR you can get that base64 string as a promise response.

function readFile(file) {
    return new Promise(resolve, reject) {
        let myReader = new FileReader();
        myReader.onloadend = function (e) {
            resolve(myReader.result);
        };
        myReader.readAsDataURL(file);
    }
};
readFile(file)
.then(function(base64string){
    /*do next steps here like sending image base64string to the server. you can send this in the body of request and in backend, receive in req.body.*/
})

Isomorphic JavaScript – The New Trend

In server side you can save the image using file system module.

import fs from 'fs';

    /*Download the base64 image in the server and returns the filename and path of image.*/
    function saveImage(baseImage) {
        /*path of the folder where your project is saved. (In my case i got it from config file, root path of project).*/
        const uploadPath = "/home/documents/project";
        //path of folder where you want to save the image.
        const localPath = `${uploadPath}/uploads/images/`;
        //Find extension of file
        const ext = baseImage.substring(baseImage.indexOf("/")+1, baseImage.indexOf(";base64"));
        const fileType = baseImage.substring("data:".length,baseImage.indexOf("/"));
        //Forming regex to extract base64 data of file.
        const regex = new RegExp(`^data:${fileType}\/${ext};base64,`, 'gi');
        //Extract base64 data.
        const base64Data = baseImage.replace(regex, "");
        const rand = Math.ceil(Math.random()*1000);
        //Random photo name with timeStamp so it will not overide previous images.
        const filename = `Photo_${Date.now()}_${rand}.${ext}`;
        
        //Check that if directory is present or not.
        if(!fs.existsSync(`${uploadPath}/uploads/`)) {
            fs.mkdirSync(`${uploadPath}/uploads/`);
        }
        if (!fs.existsSync(localPath)) {
            fs.mkdirSync(localPath);
        }
        fs.writeFileSync(localPath+filename, base64Data, 'base64');
        return {filename, localPath};
    }

Regular Expressions: Part I (The String Story)

Sending images to server via FormData and save image at server machine using multer.

Since you are sending the direct file over the server, so your request Content-Type will be multipart/form-data, therefore on nodeJs server, you will not get anything in request body. So we will use multer to handle such kind of data, we will use multer as a middleware to get the FormData.

For getting file we will use previous method.
Consider you have a input type file having name as ‘avatar’

<input type="file" id="myFile"  name="avatar">

You can get file as

let file = document.getElementById("myFile").files[0];

EC2 Node Js – HTTPS for Node.js on AWS – Install SSL AWS EC2

if you are working with AngularJs and ReactJs, you can use onChange event and get the event when file is selected

<input type="file" name="avatar" id="myFile" onChange={this.handleFile}>   //reactJs
<input name="avatar" type="file" (change)="handleFile($event)" />  //Angular

function handleFile(event) {
    let file = event.target.files[0];
}

Put file in the form data and append it in the request.

let fd = new FormData();
fd.append("file", file);

In node server we will setup the multer configuration. We will configure the upload path where file should be saved on server.

import fs from 'fs';
import Multer from 'multer';
import path from 'path';
import config from './../../config';  //configuration file to get project root path
//name of the input type (avatar in our case).
const FILENAME = 'avatar';

const uploadDir = config.get('path_project') + '/' +'uploads/';
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
}

/**
*	multer setting for photo upload storage and imagename setting, also
*	set the file details in request object
*/
let photoStorage = Multer.diskStorage({
    destination: function (req, file, cb) {
       cb(null, uploadDir)
   },
   filename: function (req, file, cb) {
        cb(null, "Photo" + '_' + Date.now() + path.extname(file.originalname));
   }
})

/**
*	Function to set storage for single upload, named as FILENAME
*/
let singleFileUpload = () => {
    return Multer({
        storage : photoStorage
    }).single(FILENAME);
}

module.exports.photoUpload = singleFileUpload;

In the route where file will be uploaded add above as a middleware.
e.g.

app.use(“/saveImage”, photoUpload(), controller);

function controller(req, res) {
/**
*   You will get image details in req.file (path where image is saved and name of the image), and if you send any other data you will get it in req.body.
*/
    localPath = req.file.destination;
    filename = req.file.filename;
}

Other articles from Cronj:

React Portal: Portals in react js

Benefits of using Node.js for business applications

HTTP 2: Future of web | fundamentals of HTTP/2

The firebase guide

GitHub is a community thing.

What is Node JS and why would I want to use it?

AngularJS and Node.js – Try and adopt for better software experience

Javascript – ES7 , ES8 New Features

Migration using JavaScript Technologies

Git Basics

The chat processes teaches a great deal about NodeJS.

Summary
Article Name
How to upload Image to Node.js and Express.js using javascript?
Description
In web application development most of the time you need to upload images and other files like pdf, docs etc. So in this blog, I will show you two ways to upload images to nodeJs server and ExpressJs server using Javascript. One is using sending image data as base64 string to server and other is to send as multipart/form-data.
Author
Publisher Name
Cronj IT Technologies Pvt Ltd
Publisher Logo

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.