I have come across many articles regarding uploading of files using mutler, but doing so we store the files in the server and there are many services that offer third party services for storage. One such service is cloudinary and the trade-offs are very good.

Although the documentation for cloudinary service is pretty good, it never mentioned the whole workflow and I had to figure it out on my own, so I am writing this article to make it easier for other people and not spend much time for that aspect.

If you would like to look at the project I have used it for, click here

The frontend would be like

<form action="/" enctype="multipart/form-data" method="POST">

<div class="form-group"> Data or Responses file <input class="form-control" name="dataFile" type="file"> </div>

</form>

The backend would be like

Package.json:

{

"name": "google_templates",

"version": "1.0.0",

"description": "",

"main": "app.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1", "start": "node app.js",

"start1": "nodemon app.js"

},

"author": "Vikranth Kanumuru",

"license": "ISC",

"dependencies": {

"body-parser": "^1.18.2",

"cloudinary": "^1.11.0", --------->cloudinary npm module

"connect-flash": "^0.1.1",

"connect-multiparty": "^2.2.0", --------->frontend uploading files

"dotenv": "^4.0.0",

"ejs": "^2.5.7",

"express": "^4.16.1",

"express-session": "^1.15.6",

"fs": "0.0.1-security",

"method-override": "^2.3.10",

"mongoose": "^4.12.1",

"nodemailer": "^4.6.8",

"passport": "^0.4.0",

"passport-local": "^1.0.0",

"passport-local-mongoose": "^4.4.0"

},

"devDependencies": {

"morgan": "^1.9.1" } }

Routing Code :

var express = require("express");

var mongoose = require("mongoose"); var fs = require("fs");

var cloudinary = require("cloudinary").v2; var multipart = require("connect-multiparty");

var multipartMiddleware = multipart(); //Enter your credentials below cloudinary.config({cloud_name: "",

api_key: "",

api_secret: ""

}); var router = express.Router(); router.post("/", multipartMiddleware, function(req,res) { let filename = req.files.dataFile.path; cloudinary.uploader.upload(filename,{ tags: "gotemps",resource_type: "auto" })

.then(function(file) { console.log("Public id of the file is " + file.public_id); console.log("Url of the file is " + file.url); /* Below variable template is part of my project and I have removed some of the unnecessary code so instead of template use whatever fits your situation */ template.dataFile=file.url; //save the url to your model template.save(); //save the model as you have changed it res.redirect("/templates");

})

.catch(function(err) { if (err) {

console.warn(err);

}

}); res.redirect("/templates");

}

});

});

Thank you for reading. I mostly write tutorials on the problems I have faced and whatever new tech I explore, so stay tuned for the next article.

If you found this article helpful, give me some claps 👏.

And you can follow me on Twitter.