“This is the 18th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

How do I upload images to Cloudinary

Now that we have a cool server running, let’s learn how to save our images on Cloudinary. This is just a basic introduction, so it should be fun 😊.

Cloudinary helps developers around the world easily manage images.

How do I create a Cloudinary account

To create an account, visit Cloudinary.

  1. Click on thesign upbuttontop right.
  2. Fill in the form shown accordingly.
  3. Submit the form using buttonsCreate Account.
  4. Check your email to complete by validating your email

You should be able to access your dashboard as follows:

Keep an eye on Account details. You should never disclose this information to anyone. I’m showing it to you here because this is a temporary account that I’m using only for the purposes of this tutorial.

Also check the Media Library TAB. This is where the uploaded image will appear.

If you have all these displays, then let’s rock……

How do I install Cloudinary in our project

Open the terminal and navigate to the project directory.

Execute the following command to install Cloudinary:

  npm install cloudinary --save
Copy the code

How to set up Cloudinary in our project

In the app.js file, require cloudinary to be const app = express(); :

  const cloudinary = require('cloudinary').v2
Copy the code

Next, add the configuration details from the account details on the dashboard as follows:

    cloud_name: 'place your cloud_name here',
    api_key: 'place your api_key here',
    api_secret: 'place your api_secret here',
Copy the code

This is what I have:

  // cloudinary configuration
  cloudinary.config({
    cloud_name: "dunksyqjj",
    api_key: "173989938887513",
    api_secret: "ZPLqvCzRu55MaM1rt-wxJCmkxqU"
  });
Copy the code

How to create an endpoint image

To avoid errors in our code, first replace the existing API with the following code:

  app.get("/", (request, response) => {
    response.json({ message: "Hey! This is your server response!" });
  });
Copy the code

It’s basically the same, but this time, we replace the use verb with the get verb and add a root endpoint (/).

Module. exports = app; Before the line, we will create our image-Uploadapi. Let’s put this code there first:

// image upload API
app.post("/upload-image", (request, response) => {});
Copy the code

Basically, that’s how we set up our API. APIPOST Request tells the server that the server should handle request with some degree of security. It makes the request with two arguments: an end-point(/upload-image) and a callback function((request, response) => {}).

Let’s build the callback function.

How to build a callback function

The installationText parser

The NPM package enables us to process incoming requests using either req.body or Request. body as appropriate. We installed body-Parser using the following code:

  npm install --save body-parser
Copy the code

Configure body-paser for our project

Body-parse is required in app.js as follows:

const bodyParser = require('body-parser');
Copy the code

Next, add the following code to set its JSON functionality as the global middleware for our application, as shown below:

  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
Copy the code

We can now process our request body appropriately.

Back to building our functionality

In the function, add the following code to collect any data entered by the user (image) :

    // collected image from a user
    const data = {
        image: request.body.image,
    };
Copy the code

Next, Cloudinary uploads the image using the following code:

cloudinary.uploader.upload(data.image);
Copy the code

Basically, that’s all we need to upload the image. So our app.js looks like this:

const express = require("express");
const app = express();
const cloudinary = require("cloudinary").v2;
const bodyParser = require('body-parser');

// body parser configuration
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// cloudinary configuration
cloudinary.config({
  cloud_name: "dunksyqjj",
  api_key: "173989938887513",
  api_secret: "ZPLqvCzRu55MaM1rt-wxJCmkxqU"
});

app.get("/", (request, response) => {
  response.json({ message: "Hey! This is your server response!" });
});

// image upload API
app.post("/image-upload", (request, response) => {
    // collected image from a user
    const data = {
      image: request.body.image,
    }

    // upload image here
    cloudinary.uploader.upload(data.image);
    
});

module.exports = app;
Copy the code

Now this looks good, and it works well. You can use Postman. But it would be great if our application could give us feedback after processing our request, right?

To achieve this, we will then… catch… Add the following block to the cloud upload, as follows:

    // upload image here
    cloudinary.uploader.upload(data.image)
    .then((result) => {
      response.status(200).send({
        message: "success",
        result,
      });
    }).catch((error) => {
      response.status(500).send({
        message: "failure",
        error,
      });
    });
Copy the code

So our final code will be:

const express = require("express");
const app = express();
const cloudinary = require("cloudinary").v2;
const bodyParser = require('body-parser');

// body parser configuration
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// cloudinary configuration
cloudinary.config({
  cloud_name: "dunksyqjj",
  api_key: "173989938887513",
  api_secret: "ZPLqvCzRu55MaM1rt-wxJCmkxqU"
});

app.get("/", (request, response) => {
  response.json({ message: "Hey! This is your server response!" });
});

// image upload API
app.post("/image-upload", (request, response) => {
    // collected image from a user
    const data = {
      image: request.body.image,
    }

    // upload image here
    cloudinary.uploader.upload(data.image)
    .then((result) => {
      response.status(200).send({
        message: "success",
        result,
      });
    }).catch((error) => {
      response.status(500).send({
        message: "failure",
        error,
      });
    });
    
});

module.exports = app;
Copy the code

How do WE test our API

Create a folder/directory in the root directory and name it images like this:

 mkdir images
Copy the code

Copy the image you selected to this folder. (The image path relative to the app.js file should now look like this: “images/

.)
“>

Now let’s move on to Postman.

  1. In the address bar, type:http://localhost:3000/image-upload
  2. willHeaderThe key is set toContent-TypeThe value is set toapplication/json
  3. Will be set tobodywejsonThe data declared in the code looks like this:
       {
	   "image": "images/oskar-yildiz-gy08FXeM2L4-unsplash.jpg"
       }
Copy the code

Click the Send button and wait for the upload to complete and get your reply:

Now, this is the result. The image now has onepublic_idUnique images randomly generated by Cloudinary, and onesecure_urlGlobally accessible images that you can load into your browser to view.

Finally, check the TAB on the Media LibraryCloudinary dashboard and you should have a new image with a new badge. Public_id This will have a unique ID that matches the one we saw in the mailman result above, as shown below:

A: wow! We stick to the image…… without pressure It feels good.

Well, one more thing — safety!

Our Cloudinary configuration details are available in our app.js file. If we push the project to GitHub, it’s publicly available to anyone who wants to see it. If it falls into the wrong hands, that could be a problem.

But don’t worry about anything here, almost everything in this space has a fix. We will use the DotenvnPM package to hide our configuration from the public.

How do we protect our configurationdotenv

First, if you do not already have DotenV installed, you need:

npm install dotenv --save
Copy the code

Then Dotenv asks app.js:

  require('dotenv').config()
Copy the code

Create a new file in the root directory and name it.env.

In the file, enter your Cloudinary configuration details as follows:

  CLOUD_NAME=dunksyqjj
  API_KEY=173989938887513
  API_SECRET=ZPLqvCzRu55MaM1rt-wxJCmkxqU
Copy the code

In the app.js file, we will use.env to access the configuration in the file through the process.env property, as shown below:

// cloudinary configuration
cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.API_KEY,
  api_secret: process.env.API_SECRET
});
Copy the code

Here is my current app.js code:

const express = require("express");
const app = express();
const cloudinary = require("cloudinary").v2;
const bodyParser = require('body-parser');
require('dotenv').config()

// body parser configuration
app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));

// cloudinary configuration
cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.API_KEY,
  api_secret: process.env.API_SECRET
});

app.get("/", (request, response, next) => {
  response.json({ message: "Hey! This is your server response!" });
  next();
});

// image upload API
app.post("/image-upload", (request, response) => {
    // collected image from a user
    const data = {
      image: request.body.image,
    }

    // upload image here
    cloudinary.uploader.upload(data.image)
    .then((result) => {
      response.status(200).send({
        message: "success",
        result,
      });
    }).catch((error) => {
      response.status(500).send({
        message: "failure",
        error,
      });
    });
});

module.exports = app;
Copy the code

Let’s test our application again to make sure there are no problems. Here are my results:

I now have two images of the same but different public_id of s.

That’s it!

Yeah! Our application is more secure than when we started.

conclusion

In this tutorial, we walk through the steps of creating a server using only Node.js. After that, we improved our servers using Express and Nodemon.

Finally, we saw how to upload images to Cloudinary via the Express application and how to secure our configuration details using the Dotenv package.

This is just an introduction. You can do a lot more if you use this application.