Uploading files in React.js Node.js on Cloud using Cloudinary

If you are creating a MERN website/web app and want to host on a platform that does not provide file storage system, Cloudinary can be one of the best options for managing files. In this tutorial we will be learning how we can upload files on Cloudinary in React.js and Node.js (Express.js).

Cloudinary

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.

Pricing

Cloudinary offers 4 different packages i.e. Free, Plus, Advanced and Enterprise. In this tutorial we will be using Free tier as it is best for small projects.

What does Free tier offer

The Free tier is free forever without needing to enter Credit Cards details. It allows 3 Users/1 Account with 25 Credits monthly. It allows 25k monthly transformation, 25GB managed storage or 25GB Net viewing Bandwidth.

Now that we know what is Cloudinary and why it is most suitable, let’s get started with our actual project.

This the previous I wrote an article on uploading files with Multer in MERN. You can read it here. We will be continuing the same project. To get started you can clone it from my GitHub repo from this link.

Recap

So earlier in our another tutorial (link) we learned to upload file using Multer via React.js and Node.js (Express). In this article we will be continuing the same thing, rather than saving those images in our local project folder we will be uploading it on cloud using Cloudinary.

Getting started

Now if you have cloned the repo, you’ll see a folder called Multer inside it we have multiple folder and one of them is backend. We have already created our frontend in previous blog and will only work on backend this time.

Now first, we will install few dependencies. To install them we will navigate to our backend folder and execute this command in terminal.

npm install cloudinary multer-storage-cloudinary dotenv

In the mean while if you do not have a cloudinary account you can create one at https://cloudinary.com/users/register_free

Now once your have successfully registered, you need to note down your cloudinary “cloud name”, “api_key” and “api_secret” because we will be using it. Now since this needs to be kept private we need to add it in “.env” file. Let’s make one. To make an env file, just click on the file icon and create new file.

Now once its create let’s copy paste the variables. We will be using them to configure our cloudinary.

cloud_name: ""cloud_api_key: ""cloud_api_secret: ""

Now paste all cloud name, api_key and api_secret that you got from cloudinary after creating an account.

Next, we will edit our file route. We will remove the multer config and add another one that supports multer with cloudinary.

You code will look like this:

const express = require("express");const fileController = require("../controllers/fileController")const fileRouter = express.Router();const multer  = require('multer')const cloudinary = require('cloudinary').v2;const { CloudinaryStorage } = require('multer-storage-cloudinary');cloudinary.config({cloud_name: process.env.cloud_name,api_key: process.env.cloud_api_key,api_secret: process.env.cloud_api_secret});const storage = new CloudinaryStorage({cloudinary: cloudinary,params: {folder: "DEV",allowedFormats: ['png', 'jpg', 'jpeg'],width: 250, height: 250, crop: "fill"},});const upload = multer({ storage: storage });fileRouter.route("/upload").post(upload.single('image'), fileController.fileUpload);module.exports = fileRouter;

Now let’s understand what we are doing here.

So firstly, we are configuring our cloudinary with its default function .config. We are taking values from .env file that is why it starts with process.env. Next, we are setting up the storage and passing few options. Here I am resizing all incoming images to 250px250px, but it is not needed. Next, we are telling multer to user the above storage configs.

Now once our route is changed, we need to make few changes in our file controller.

Again, in our controller we will import our packages and configuring our cloudinary using env file data.

Now, we will edit our file upload function. Now we will first check if we are getting our file in backend function if so, then we will run cloudinary uploader function and display the url that cloudinary returned us.

const result = await cloudinary.uploader.upload(req.file.path);console.log(result.url)

Complete controller code.

const moment = require("moment");const cloudinary = require('cloudinary').v2;const { CloudinaryStorage } = require('multer-storage-cloudinary');cloudinary.config({cloud_name: process.env.cloud_name,api_key: process.env.cloud_api_key,api_secret: process.env.cloud_api_secret});const fileUpload = async (req, res)=>{try{if(req.file){const result = await cloudinary.uploader.upload(req.file.path);res.status(200).send({ status: "success", message: `${req.file.originalname} uploaded!` })}else{res.status(404).send({ status: "error", message: `File not found!` })}} catch(err){console.log(err)res.status(500).send({ status: "err", error: err })}}module.exports = {fileUpload}

One last thing!

Now one last thing, since we are using .env to store our api key, secret and cloud name. To use those values we need to the below line on top of our server.js file. It will tell our server to access those values from env file.

require('dotenv').config()

GitHub Repo for this article: https://github.com/MuqtadirBillah/mern-cloudinary

Now we know how to upload file on Cloudinary using MERN stack.

Follow me for more interesting tips and tricks at Musab Abbasi — Medium
You can also find me on LinkedIn and Github

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi

88 Followers

Computer Science Graduate with MERN stack website development expertise.