How to Upload Images to Cloudinary in Node.js Projects?

As we mentioned in the previous post, we usually store the uploaded image on some storage servers, such as AWS S3, and Cloudinary… However, wow to upload images to Cloudinary in Node.js projects?

By the way, Cloudinary also with a free forever solution for developers, it is NO credit card required. It includes:

  • 25k Monthly Transformations or
  • 25GB Managed Storage or
  • 25GB Monthly Net Viewing Bandwidth

It’s very easy to implement the function of uploading images to Cloudinary in Node.js projects.

How to Upload Images to Cloudinary Node.js

How to upload images to Cloudinary in Node.js projects?

1. Set enctype="multipart/form-data" in the image upload HTML page.

<div class="col-6 offset-3">
      <form action="/campgrounds" novalidate class="d-inline form-validation" method="POST"
        enctype="multipart/form-data">
        <div class="mb-3">
          <span>Upload an image: </span><input type="file" name="image" id="image" multiple />
        </div>
      </form>
</div>

2. Install Multer middleware

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.

$ npm install --save multer

Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

3. Register Cloudinary

In this step, we can choose to register a free plan account to use Cloudinary to store our images.

4. Configure and use Cloudinary Node SDK

npm install cloudinary

To init the Cloudinary configure in the cloudinary/index.js:

const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

const storage = new CloudinaryStorage({
    cloudinary,
    folder: 'FAQgeek',
    allowedFormats: ['jpeg', 'png', 'jpg']
});

module.exports = {
    cloudinary, 
    storage
}

In this step, we usually write the Cloudinary API configuration in a .env file in our project. Then use dotenv to load the configuration.

5. Finish the upload process

...
const multer  = require('multer');
const { storage } = require('../cloudinary');
const upload = multer({storage});

router.route('/').post(upload.array('image'), (req, res) => {
        console.log(req.body, req.files);
        res.send('It works!');
    })

Now, we can choose images to upload to Cloudinary in the HTML page. And we can see the returned information about the uploaded images in the terminal or check the images on the Cloudinary dashboard.