How To Use Cloudinary For FileUploading In Node

Introduction

 
In this article we see how to create an application from scratch where we will upload a file to the cloudinary cloud and save that file's url in the db and then display it on the page.
 
Prerequisite

Project Structure

 
|------------ views
                     |------------ home.ejs
 
|------------ app.js 
  
|------------ package.json 
 

What Is Cloudinary? 

 
Cloudinary is a service that manages an application’s image and video-related needs all in the cloud.Cloudinary allows users to effortlessly upload and store images and videos to the cloud. Users also no longer need separate programs to resize, crop, convert, and perform other similar actions as the service offers comprehensive editing capabilities. Images are served through Akamai’s worldwide CDN for quick and responsive delivery that is optimized for all devices. Cloudinary is thus a digital asset management platform with a media library that utilizes SDKs and RESTful APIs to automate image management.
 

What Is Multer?

 
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.
For more information click here.
 

Project Setup

 
Lets setup our workspace,
  • Open the console and type mkdir followed by the directory name
  • Now type cd followed by the directory name.
 
Now type npm init for creating package.json file for our application.
 
You can learn about package.json file here.
 
# npm init
 
After typing this command you will be prompted with a few things related to package.json file, such as name, version, etc. Once finished, a package.json file will be generated.
 

Express Setup

 
After generating the package.json file, we will install the express framework and some other packages.
 
# npm install express mongoose multer ejs
  • The installed package will be put in the dependencies section of package.json.
  • Add a new file app.js in the root. This will be the starting point of our application.
  • Open the package.json file and in "scripts" write "start":" node app.js".
Now, add new folder named views to the project. And add file home.ejs to it.
 
 

Setup Cloudinary

 
For using cloudinary in project you should have a free account on cloudinary for using the cloudinary cloud. So if you dont have account on cloudinary then create it from here.
 
So first create the account.
 
Now let's start by installing cloudinary in our project,
 
# npm install cloudinary
 
After this open the app.js and write the below code in it
 
app.js 
  1. var express    = require('express');  
  2. var multer     = require('multer');  
  3. var path       = require('path');  
  4. var cloudinary = require('cloudinary');  
  5. var mongoose   = require('mongoose');  
  6.   
  7. //setting up the multer engine  
  8. var storage = multer.diskStorage({});  
  9.   
  10. var upload = multer({storage:storage});  
  11.   
  12. var app = express(); 

  13. //setting the connection to the database 
  14. mongoose.connect("mongodb://localhost:27017/uploadImage",{useNewUrlParser:true})  
  15. .then(()=>console.log('connected to db')).catch((error)=>console.log('connection error',error));  
  16.   
  17. //set the collection schema  
  18. var uploadSchema = new mongoose.Schema({  
  19.     picUrl:String  
  20. });  
  21.  //it is the collection name in which our userSchema data will be stored
  22. var fileUpload = mongoose.model('pics',uploadSchema);  

  23.  //setting the template engine  
  24. app.set('view engine','ejs')  
  25.   

  26. //here you have to provide the cloud_name,api_key,api_secret value
  27. //which you will get on dashboard when you login.    
  28. cloudinary.config({  
  29.     cloud_name:"",  
  30.     api_key:,  
  31.     api_secret:""  
  32. });  
  33.   
  34. //default page
  35. app.get('/',(req,res)=>{  
  36.     fileUpload.find((error,data)=>{  
  37.         if(error){  
  38.             console.log('error',error)  
  39.         }  
  40.         else if(data){  
  41.             console.log(data)  
  42.          res.render('home',{data:data})  
  43.         }  
  44.         else{  
  45.             res.render('home',{data:null})  
  46.         }  
  47.   })  
  48. })  
  49.   
  50. app.post('/upload',upload.single('pic'),(req,res)=>{  
  51.     console.log(req.file)  

  52.        //uploading the file to the cloudinary cloud
  53.        //this will return us json data in which it will provide
  54.        //the url of the image by which we can get it from cloud
  55.         cloudinary.v2.uploader.upload(req.file.path).then(function(data){  
  56.             console.log(data.url)  
  57.             const temp = new fileUpload({  
  58.                 picUrl:data.url  
  59.             })  
  60.            //saving the data
  61.             temp.save((error,data)=>{  
  62.                 if(error){  
  63.                     console.log('error',error)  
  64.                 }  
  65.                 else{  
  66.                     res.redirect('/')  
  67.                 }  
  68.             })  
  69.         }).catch(function(error){  
  70.             console.log(error);  
  71.         })  
  72. })  
  73.   
  74. var port = process.env.PORT || 3000;  
  75. app.listen(port,()=>console.log('server run at '+port));  
After uploading the  file the cloduinarycloud will return a result in json form.
  1. {  
  2.   "public_id""4srvcynxrf5j87niqcx6w",  
  3.   "version": 1340625837,  
  4.   "signature""01234567890abcdef01234567890abcdef012345",  
  5.   "width": 200,  
  6.   "height": 200,  
  7.   "format""jpg",  
  8.   "resource_type""image",  
  9.   "url""http://res.cloudinary.com/demo/image/upload/v1340625837/4srvcynxrf5j87niqcx6w.jpg",  
  10.   "secure_url""https://res.cloudinary.com/demo/image/upload/v1340625837/4srvcynxrf5j87niqcx6w.jpg"  
  11. }  
  • In the above code in post we are fetching the url from data.url and saving it in our db collection.       
  • mongoose.connect() -> Will setup the connection with local db on our system.
  • localhost:27017/uploadImage -> uploadImageis the name of our database which will be created on the server.
  • app.set("view engine","ejs") -> This tells express that any file ending in .ejs should be rendered with ejs packages.
  • mongoose.Schema({}) -> Contains the fields of our collection(table).
  • mongoose.model() -> Contains collection(table) name and the object containing collection(table) field data.
  • cloudinary.config() ->This will contain the cloud name, apikey, and apisecret which you will get on your cloudinary dashboard.
  • upload('pic') ->With this, we need to provide the same name as the name attribute which we used to upload the file.pic. It is the same name which is given in the name attribute. <input type="file"name="pic">. 
Views 
 
home.ejs 
  1.  <html lang="en">    
  2.  <head>    
  3.      <meta charset="UTF-8">    
  4.      <meta name="viewport" content="width=device-width, initial-scale=1.0">    
  5.      <meta http-equiv="X-UA-Compatible" content="ie=edge">    
  6.      <title>Document</title>    
  7.       <!-- Compiled and minified CSS -->    
  8.     <link rel="stylesheet" href="https://bootswatch.com/4/pulse/bootstrap.css">    
  9.   <link rel="stylesheet" href="https://bootswatch.com/_assets/css/custom.min.css">    
  10.  </head>    
  11.  <body>    
  12. <div>    
  13.         <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">    
  14.                 <a class="navbar-brand" href="/">ClodinaryDemo</a>    
  15.                 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">    
  16.                   <span class="navbar-toggler-icon"></span>    
  17.                 </button>    
  18.               </nav>    
  19. </div>    
  20.     
  21.      <div style="display: block; width: 450px;">    
  22.             <form action="/upload" method="post" enctype="multipart/form-data">                    
  23.                       <div class="form-group">    
  24.                         <label for="pic">File input</label>    
  25.                       <input type="file" class="custom-file" id="pic" name="pic">    
  26.                       </div>    
  27.                       <button type="submit" class="btn btn-primary">Submit</button>    
  28.             </form>    
  29.       </div>    
  30.       <div class="container">    
  31.           <%if(data.length>0){%>    
  32.             <table  class="table table-hover">    
  33.                     <thead>    
  34.                       <tr>    
  35.                         <th>S.no</th>    
  36.                         <th>pic</th>    
  37.                       </tr>    
  38.                     </thead>    
  39.                     <tbody>    
  40.                         <%for(var i=0; i< data.length; i++){%>                              
  41.                       <tr>    
  42.                           <td><%= i%></td>    
  43.                         <td><img src="<%= data[i].picUrl%>" alt="" style="width:120px;height:120px;"></td>    
  44.                       </tr>     
  45.                       <%}%>    
  46.                     </tbody>    
  47.                   </table>    
  48.                   <%}%>     
  49.       </div>    
  50.         
  51.  </body>    
  52.  </html>  

Summary

 
We saw how we can upload our file to the cloduinary cloud.