Upload files to Cloudinary using vanilla JS

Upload files to Cloudinary using vanilla JS

ยท

4 min read

Hi everyone, in this blog we are going to create a solution that you can use in isolation or integrate into your project if you want to store your images in the cloud. We are going to use Cloudinary for this purpose.

Outline

  • Pre Requisites
  • HTML Code
  • CSS Code
  • Cloudinary Logic

Pre Requisites

  1. Have an account on Cloudinary. if you don't have one already you can grab yours here
  2. Basic knowledge of HTML, CSS JS (network requests and DOM Manipulation to be specific).
  3. Working Network Connection.
  4. Beautiful images to upload ๐Ÿ˜œ

HTML Code

<div class="card">
  <h1> Upload Image </h1>
  <div class="box"></div>
  <div class="input-box">
    <label for="file">Choose File</label>
  <input type="file" class="input" id="file">
  </div>
</div>

This is a very simple HTML Code. There is nothing much to explain here, but I would like to point to label and input tag please make sure you give the value to for attribute in label same as your value of id attribute in input

Because we will hide the actual input tag from the page (because it looks ugly. Please agree with me here ๐Ÿ˜‚). So, the label tag will be used to access the input tag.

CSS Code

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body{
  font-family: sans-serif;
  min-height: 100vh;
  display:grid;
  place-items:center;
  background: violet;
}
.card{
  max-width: 400px;
  width: 100%;
  padding: 2rem 0;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 20px 20px  rgba(0,0,0,0.2);
  display: flex;
  flex-direction: column;
  gap: 15px;
  justify-content: center;
  align-items: center;
}
h1{
  font-size: 14px;
  color: gray;
}
.box{
  background: #C7DFC5;
  width: 300px;
  height: 200px;
  overflow: hidden;
  border-radius: 8px;
}
input{
  display: none;
}
label{
  display: inline-block;
  background-color: #313B72;
  color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
  margin-top: 10px;
  cursor:pointer;
}

After writing HTML and CSS you should have something like this in your browser.

Capture.PNG

I know I know it's not the most beautiful design in the world ๐Ÿ˜‚. I leave it to you guys to make it beautiful because our focus is on the working logic here. Right? ๐Ÿ˜

Cloudinary Logic

Now, let's come to the main ingredient part of our recipe ๐Ÿ• (Pizza to keep you here ๐Ÿ˜œ)

First of all, please visit your dashboard on Cloudinary and copy your cloud name from there.

Capture.PNG

Also, we need to have an upload preset that we can use for unsigned signatures. You can grab this from

Settings --> Upload Then scroll down

image.png

image.png

Create your unsigned preset from here.

There are two ways to use the Cloudinary SDK

  • using npm
  • using CDN

In this blog, we will be using the CDN method.

Use the following three scripts and paste them before your app.js script

<script
      src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"
      integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/cloudinary-core/2.11.4/cloudinary-core.min.js"
      integrity="sha512-IbSnv7d3S0AhZSFfPStsTG9IfssskLtgsm2gbbTjmFM/ssHMIwwwRItZfGQKZYhwVXStAVT7nA+pdu0VTE01lA=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"
      integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>

These three scripts are for

  1. Lodash (used internally by Cloudinary)
  2. Cloudinary
  3. Axios (to make network requests, because we won't be using fetch API ๐Ÿ˜‰).

endpoint where you need to make your post request is

https://api.cloudinary.com/v1_1/${cloudName}/upload

Now open your app.js file and do the following.

var cl = new cloudinary.Cloudinary({ cloud_name: "codermj", secure: true });
const CLOUDINARY_URL = "https://api.cloudinary.com/v1_1/codermj/upload";
const CLOUDINARY_UPLOAD_PRESET = "n8hb45ip";

Please use your own cloud_name which you grabbed from the Cloudinary dashboard earlier.

input.addEventListener("change", (e) => {
  const file = e.target.files[0];
  uploadFile(file);
});

We want to upload our files whenever we have a file in the input tag. So, we will be using the change event. You can grab your uploaded file in JS via e.target.files[0].

function uploadFile(file) {
  let formData = new FormData();
  formData.append("file", file);
  formData.append("upload_preset", CLOUDINARY_UPLOAD_PRESET);

  axios({
    url: CLOUDINARY_URL,
    method: "POST",
    data: formData,
  })
    .then((res) => {
      box.style.background = `url('${res.data.secure_url}')`;
      box.style.backgroundSize = "cover";
      box.style.backgroundPosition = "center";
    })
    .catch((err) => console.log(err));
}

Cloudinary doesn't want the incoming data to be in JSON format so we need to make a new instance of FormData() and then append your file as well as upload preset to this formdata.

When we make a network request here, we will get a lot of data in the response object. But the thing we need to grab is accommodated on this path (res.data.secure_url). This is nothing but a URL to access your image.

In our code, we are using this URL to show the uploaded image as a background image in the box.

In the end, we will have the following-looking page.

image.png

Where to go from here?

  1. You can add the uploading animation between your initial and final state you can have beautiful animation on your page.
  2. You can enhance the functionality by using Drag and Drop API to upload images.
  3. Explore the Cloudinary documentation for things like cropping, resizing images, etc.

Conclusion

In this blog, we have created a solution to upload our files to the cloud. We've not used any javascript library or framework for this.

Checkout the finished version

I hope I was able to deliver something good to you guys โ˜บ. Feedbacks, suggestions, etc are always welcomed.

Have a fun and safe time and Thank you so much for dedicating your time to go through this blog โค.

Let's Learn and Grow Together. Adios amigos/amigas hasta la proxima vez ๐Ÿ’œโ˜•