Node.js, Express.js and Multer Restful API for Image Uploader

by Didin J. on mar 25, 2019 Node.js, Express.js and Multer Restful API for Image Uploader

A short step by step tutorial on REST API for Image Uploader using Node.js, Express.js and Multer

A short step by step tutorial on REST API for Image Uploader using Node.js, Express.js, and Multer. We are using the form `multipart/form-data` `enctype` for upload image using REST API service. To make it simple we are using Multer Node.js library/module. Now, we will show you how to use it from scratch.


Table of Contents:


The following tools, frameworks, and modules are required for this tutorial:

  1. Node.js
  2. Express.js
  3. Multer
  4. Terminal or Command Line
  5. Text Editor or IDE
  6. Postman

We assume that you have to install Node.js on your machine and can run `node`, `npm` or `yarn` command in your terminal or command line. Next, check their version by type this commands in your terminal or command line.

node -v
v10.15.1
npm -v
6.8.0
yarn -v
1.10.1

That the versions that we are uses. Let's continue with the main steps.


Create New Express.js Application and Required Modules

We will start this tutorial by creating or generating web or REST API application using Express.js. Open your terminal or node command line the go to your projects folder. First, install express-generator using this command.

sudo npm install express-generator -g

Next, create an Express.js app using this command.

express image-uploader

Next, go to the newly created project folder then install node modules.

cd image-uploader && npm install

There's no view yet using the latest Express generator. We don't need it because we will create a REST API server. Next, install modules for uploading an image.

npm install --save multer

Now, you are ready to create REST API service for image upload.


Implementing Image Upload in REST API Route

We will use an existing route for image upload endpoint. Open and edit `app.js` then change this line.

app.use('/', index);

To this line.

app.use('/api/', indexRouter);

Next, open and edit `routes/index.js` then add this required variables that implementing Multer for uploading the image to Express.js server storage .

var multer  = require('multer');
var storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, './public/images');
    },
    filename: (req, file, cb) => {
      console.log(file);
      var filetype = '';
      if(file.mimetype === 'image/gif') {
        filetype = 'gif';
      }
      if(file.mimetype === 'image/png') {
        filetype = 'png';
      }
      if(file.mimetype === 'image/jpeg') {
        filetype = 'jpg';
      }
      cb(null, 'image-' + Date.now() + '.' + filetype);
    }
});
var upload = multer({storage: storage});

As you can see, we are saving the image file in `public/images` folder and give a name to the image file as `image-date`. If there's no images folder exists, create one inside the public folder. Next, create a new route for image upload.

router.post('/upload',upload.single('file'),function(req, res, next) {
  console.log(req.file);
  if(!req.file) {
    res.status(500);
    return next(err);
  }
  res.json({ fileUrl: 'http://192.168.0.7:3000/images/' + req.file.filename });
})

That REST API sends a response of Image file URL that accessible to Express.js web server.


Run and Test the Node.js, Express.js and Multer Image Uploader

To test this Express.js application, just run this command.

nodemon

or

npm start

Next, open the Postman application then change the method to `POST` and the URL to `http://localhost:3000/api/upload`. Change the body to `form-data` then fill the key as file and pick an image file. You can see the Postman request as below.

Node.js, Express.js and Multer Restful API for Image Uploader - Postman Image Upload

You will see this response for a successful upload.

{
    "fileUrl": "http://192.168.0.7:3000/images/image-1553473134646.png"
}

Now, you can check the uploaded image by entering that address from the API response.

That it's, our simple tutorial of creating Image Uploader using Node.js, Express.js, and Multer. You can get the full source code from our GitHub.

That just the basic. If you need more deep learning about MEAN Stack, Angular, and Node.js, you can take the following cheap course:

Thanks!

Loading…