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.
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.
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
- var express = require('express');
- var multer = require('multer');
- var path = require('path');
- var cloudinary = require('cloudinary');
- var mongoose = require('mongoose');
-
- //setting up the multer engine
- var storage = multer.diskStorage({});
-
- var upload = multer({storage:storage});
-
- var app = express();
- //setting the connection to the database
- mongoose.connect("mongodb://localhost:27017/uploadImage",{useNewUrlParser:true})
- .then(()=>console.log('connected to db')).catch((error)=>console.log('connection error',error));
-
-
- var uploadSchema = new mongoose.Schema({
- picUrl:String
- });
- //it is the collection name in which our userSchema data will be stored
- var fileUpload = mongoose.model('pics',uploadSchema);
- //setting the template engine
- app.set('view engine','ejs')
-
- //here you have to provide the cloud_name,api_key,api_secret value
- //which you will get on dashboard when you login.
- cloudinary.config({
- cloud_name:"",
- api_key:,
- api_secret:""
- });
-
- //default page
- app.get('/',(req,res)=>{
- fileUpload.find((error,data)=>{
- if(error){
- console.log('error',error)
- }
- else if(data){
- console.log(data)
- res.render('home',{data:data})
- }
- else{
- res.render('home',{data:null})
- }
- })
- })
-
- app.post('/upload',upload.single('pic'),(req,res)=>{
- console.log(req.file)
- //uploading the file to the cloudinary cloud
- //this will return us json data in which it will provide
- //the url of the image by which we can get it from cloud
- cloudinary.v2.uploader.upload(req.file.path).then(function(data){
- console.log(data.url)
- const temp = new fileUpload({
- picUrl:data.url
- })
- //saving the data
- temp.save((error,data)=>{
- if(error){
- console.log('error',error)
- }
- else{
- res.redirect('/')
- }
- })
- }).catch(function(error){
- console.log(error);
- })
- })
-
- var port = process.env.PORT || 3000;
- app.listen(port,()=>console.log('server run at '+port));
After uploading the file the cloduinarycloud will return a result in json form.
- {
- "public_id": "4srvcynxrf5j87niqcx6w",
- "version": 1340625837,
- "signature": "01234567890abcdef01234567890abcdef012345",
- "width": 200,
- "height": 200,
- "format": "jpg",
- "resource_type": "image",
- "url": "http://res.cloudinary.com/demo/image/upload/v1340625837/4srvcynxrf5j87niqcx6w.jpg",
- "secure_url": "https://res.cloudinary.com/demo/image/upload/v1340625837/4srvcynxrf5j87niqcx6w.jpg"
- }
- 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
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- <!-- Compiled and minified CSS -->
- <link rel="stylesheet" href="https://bootswatch.com/4/pulse/bootstrap.css">
- <link rel="stylesheet" href="https://bootswatch.com/_assets/css/custom.min.css">
- </head>
- <body>
- <div>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
- <a class="navbar-brand" href="/">ClodinaryDemo</a>
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
- </nav>
- </div>
-
- <div style="display: block; width: 450px;">
- <form action="/upload" method="post" enctype="multipart/form-data">
- <div class="form-group">
- <label for="pic">File input</label>
- <input type="file" class="custom-file" id="pic" name="pic">
- </div>
- <button type="submit" class="btn btn-primary">Submit</button>
- </form>
- </div>
- <div class="container">
- <%if(data.length>0){%>
- <table class="table table-hover">
- <thead>
- <tr>
- <th>S.no</th>
- <th>pic</th>
- </tr>
- </thead>
- <tbody>
- <%for(var i=0; i< data.length; i++){%>
- <tr>
- <td><%= i%></td>
- <td><img src="<%= data[i].picUrl%>" alt="" style="width:120px;height:120px;"></td>
- </tr>
- <%}%>
- </tbody>
- </table>
- <%}%>
- </div>
-
- </body>
- </html>
Summary
We saw how we can upload our file to the cloduinary cloud.