How To Store Image In Cloudinary Nodejs Rest

May 25, 2019 (5y ago)

Last week, I’m building my side project using this VEMN stack – (Vue, Express, Mongo, Node). My backend needs to use REST to interact with the Front-end. I need to store the images assets which are uploading by the end user. I do some survey to find what is the best way to store an image for the web application. I found there is two good company provide these services which are Cloudinary and Imgix.

Imgix has a reasonable pricing compare to Cloudinary but Cloudinary has a free package. Since my side project is still in MVP and I want to validate this idea, I decided to go with Cloudinary.

This is what you need

Register an account with cloudinary first. Don’t worry it’s free.

How to store the image in Cloudinary Nodejs REST 2

Install this package

I make it easier, just run this command.

    npm install --save cloudinary cloudinaryStorage multer

After everything is done, you should inject this middleware to your routes.

Configuration

Import the package first and then write a cloudinary config. You can get the cloud name, API key and API secret key on your dashboard.

    const cloudinary = require("cloudinary");
    const cloudinaryStorage = require("multer-storage-cloudinary");
    const multer = require("multer");
    const config = require("../../config/config");
    
    cloudinary.config({
      cloud_name: config.cloudinary.name,
      api_key: config.cloudinary.api_key,
      api_secret: config.cloudinary.api_secret,
    });

Define storage for your own project. You can define your folder name, format, and transformation to the images.

    const storage = cloudinaryStorage({
      cloudinary,
      folder: "jomwedding",
      allowedFormats: ["jpg", "png"],
      transformation: [{ width: 500, height: 500, crop: "limit" }],
    });
    const parser = multer({ storage });

Middleware

When everything’s done, inject your middleware to your routes.

    router.route("/image").post(parser.single("image"), userCtrl.uploadImage);

Make sure you’re using the multipart form to send the image

Example of my REST

The image will be store to the cloudinary before can be accessed in your controller. To access your stored image can be found in req.file.

    function uploadImage(req, res, next) {
      console.log(req.file);
      const image = {};
      image.url = req.file.url;
      image.id = req.file.public_id;
    }

Let me know if you have any question or problem.