How to upload single/multiple image to cloudinary using node.js ? - GeeksforGeeks

20 Jan, 2022
Cloudinary is an end-to-end image and video management solution for websites and mobile apps, covering everything from image and video uploads, storage, manipulations, optimizations to delivery.
Installation:
Step 1: Go to the project directory and initialize the project using the below command in the terminal.npm init -y
Step 1: Go to the project directory and initialize the project using the below command in the terminal.
npm init -y
Step 2: Install the required npm packages using the following command.npm install express multer cloudinary
Step 2: Install the required npm packages using the following command.
npm install express multer cloudinary
Step 3: Create 2 files in the current project directory named index.js and public/index.html as shown in the below project directory.
Step 3: Create 2 files in the current project directory named index.js and public/index.html as shown in the below project directory.
Project Structure:
index.html: It basically contains 2 forms i.e single and multiple file upload.
index.html
<!DOCTYPE html><body style="padding: 30px;">    <form method="POST" action="/profile-upload-single"           enctype="multipart/form-data">        <div>            <label>Upload profile picture</label>            <input type="file" name="profile-file" required/>        </div>        <div>            <input type="submit" value="Upload" />        </div>    </form>          <br><hr><br>      <form method="POST" action="/profile-upload-multiple"           enctype="multipart/form-data">        <div>            <label>Upload multiple profile picture</label>            <input type="file" name="profile-files" required multiple  />        </div>        <div>            <input type="submit" value="Upload" />        </div>    </form></body></html>
index.js: Replace cloud_name, api_key, api_secret with your cloudinary credentials which you can find on cloudinary dashboard.
index.js
// Requiring moduleconst express = require("express");const multer = require("multer");const port = 3000;const app = express();const cloudinary = require("cloudinary").v2;const bodyParser = require("body-parser");const fs = require("fs");  // Creating uploads folder if not already present// In "uploads" folder we will temporarily upload// image before uploading to cloudinaryif (!fs.existsSync("./uploads")) {    fs.mkdirSync("./uploads");}  // Multer setupvar storage = multer.diskStorage({    destination: function (req, file, cb) {        cb(null, "./uploads");    },    filename: function (req, file, cb) {        cb(null, file.originalname);    },});  var upload = multer({ storage: storage });  // Body parser configurationapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));  app.use(express.static(__dirname + "/public"));app.use("/uploads", express.static("uploads"));  // Cloudinary configurationcloudinary.config({    cloud_name: "YOUR_CLOUD_NAME",    api_key: "YOUR_API_NAME",    api_secret: "YOUR_API_SECRET",});  async function uploadToCloudinary(locaFilePath) {      // locaFilePath: path of image which was just    // uploaded to "uploads" folder      var mainFolderName = "main";    // filePathOnCloudinary: path of image we want    // to set when it is uploaded to cloudinary    var filePathOnCloudinary =         mainFolderName + "/" + locaFilePath;      return cloudinary.uploader        .upload(locaFilePath, { public_id: filePathOnCloudinary })        .then((result) => {              // Image has been successfully uploaded on            // cloudinary So we dont need local image             // file anymore            // Remove file from local uploads folder            fs.unlinkSync(locaFilePath);              return {                message: "Success",                url: result.url,            };        })        .catch((error) => {              // Remove file from local uploads folder            fs.unlinkSync(locaFilePath);            return { message: "Fail" };        });}  function buildSuccessMsg(urlList) {      // Building success msg to display on screen    var response = `<h1>                   <a href="/">Click to go to Home page</a><br>                  </h1><hr>`;      // Iterating over urls of images and creating basic    // html to render images on screen    for (var i = 0; i < urlList.length; i++) {        response += "File uploaded successfully.<br><br>";        response += `FILE URL: <a href="${urlList[i]}">                    ${urlList[i]}</a>.<br><br>`;        response += `<img src="${urlList[i]}" /><br><hr>`;    }      response += `<br><p>Now you can store this url in database or   // do anything with it  based on use case.</p>`;    return response;}  app.post(    "/profile-upload-single",    upload.single("profile-file"),    async (req, res, next) => {          // req.file is the `profile-file` file        // req.body will hold the text fields,        // if there were any          // req.file.path will have path of image        // stored in uploads folder        var locaFilePath = req.file.path;          // Upload the local image to Cloudinary         // and get image url as response        var result = await uploadToCloudinary(locaFilePath);          // Generate html to display images on web page.        var response = buildSuccessMsg([result.url]);          return res.send(response);    });  app.post(    "/profile-upload-multiple",    upload.array("profile-files", 12),    async (req, res, next) => {          // req.files is array of `profile-files` files        // req.body will contain the text fields,        // if there were any        var imageUrlList = [];          for (var i = 0; i < req.files.length; i++) {            var locaFilePath = req.files[i].path;              // Upload the local image to Cloudinary            // and get image url as response            var result = await uploadToCloudinary(locaFilePath);            imageUrlList.push(result.url);        }          var response = buildSuccessMsg(imageUrlList);          return res.send(response);    });  app.listen(port, () => {    console.log(`Server running on port ${port}!            \nClick http://localhost:3000/`);});
Steps to run the program:
node index.js
Output: Open the browser and visit http://localhost:3000. You could now see the following 2 forms i.e single and multiple image upload as shown below.
References: https://cloudinary.com/documentation/node_integration.
rajeev0719singh
sooda367
sagar0719kumar
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Difference between npm i and npm ci in Node.js
Mongoose Populate() Method
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript