How to upload multiple and single images to Cloudinary with just one function in NodeJs

How to upload multiple and single images to Cloudinary with just one function in NodeJs

Image upload is a very essential aspect of modern day websites. However, most beginners find it intimidating to do because they don't know what service to use or how to use the service. Therefore, I present below the step by step guide of how to upload multiple and single images to Cloudinary with just one function in NodeJs.

  • Step 1:

The first step in this process is to grab the image from the user. You can use plain HTML for it or you can use a framework e.g ReactJS. Regardless of the one you use, it still the same format.

Here we create our form in the client side.

     <form
      action="http://localhost:4006/upload"
      method="post"
      enctype="multipart/form-data"
     >

      <input type="file" name="image" id="image" multiple />
      <button type="submit">Submit</button>

    </form>
  • Step 2:

Create a Cloudinary account. Go to your cloudinary dashboard to see your account details containing your cloud name, API key and API secret.

  • Step 3:

Setup NodeJs server.

a. Create folder e.g cloudinaryUpload, and open on your favorite code editor.

b. Open terminal and initialize app by running npm init -y

c. Setup your package.json to look like the setup below:

{
    "name": "cloudinary upload,
    "version": "1.0.0",
    "description": "Your description",
    "main": "server.js",
    "scripts": {
      "start": "node server.js",
      "server": "nodemon server.js"
    },
    "keywords": "",
    "author": "Onuorah Bonaventure Chukwudi (Bonarhyme)",
    "license": "ISC",
    "dependencies": {},
    "devDependencies": {}
  }

d. Install neccessary dependencies by running npm install express nodemon cloudinary multer

e. Create server.js file and set it up like below:

const express = require("express")
const app = express()

app.use(express.json())

// Multer setup goes under here

// The route we will use
app.post("/upload", (req, res) =>{})

app.listen("4006", () => console.log("Server running on port 4006"))

f. Add multer configuration

// Multer Setup goes under here
// Multer handles the collection of files from the server
const multer = require("multer");
const storage = multer.diskStorage({});

const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image")) {
    cb(null, file.fieldname + "-" + Date.now());
  } else {
    cb("invalid image file!", false);
  }
};

const upload = multer({ storage, fileFilter });

// Cloudinary config goes under here

g. Add Cloudinary config

Import cloudinary and set it up like this using your account details from Cloudinary.

const cloudinary = require("cloudinary").v2;

// Cloudinary config goes under here
cloudinary.config({
  cloud_name: "Cloudname goes here",
  api_key:  "API key goes here",
  api_secret: "API secret goes here",
  // secure: true
});

h. Create your upload function right inside the route and it up like below. Also pass multer as a middleware.

// The route we will use
app.post("/upload", upload.array("image"), (req, res) => {    
let pictureFiles = req.files;

 if (!pictureFiles) {
    res.status(400).send("No picture attached!");
 }

// Magic function to handle both multiple and single image upload
 let multiplePicturePromise = pictureFiles.map((picture, index) =>
      cloudinaryImp.uploader.upload(picture.path, {
        public_id: `${Date.now()}_${index}`,
        height: 400,
        width: 400,
        crop: "fill",
      })
    );

})

// Get the response from cloudinary
const imageResponse = await Promise.all(multiplePicturePromise);

 const imagesUrl = imageResponse.map((image) => {
   const url = image.secure_url;
     return { url };
    });

if(imagesUrl.length > 0){
  res.send({
       message: "Image upload was successful"
       images: imagesUrl
 })

i. Start the app by running npm run server on the terminal.

Remarks

Congratulations!!! You have succeeded!!!

Please follow me on twitter Bonaventure Chukwudi

Support me on Patreon