How To Upload Image In Cloudinary Using Javascript

Cloudinary is an end-to-end image and video management system for websites and mobile apps, handling everything from the picture and video uploads through storage, modification, and optimization.

Step 1:

First, you need to create your Cloudinary account.

After than, we have to add the following script to top off the project

<script src='https://cdn.jsdelivr.net/jquery.cloudinary/1.0.18/jquery.cloudinary.js' type='text/javascript'></script>
<script src="https://widget.cloudinary.com/v2.0/global/all.js" type="text/javascript"></script>

Set your cloud name in the API URL in the code: “https://api.cloudinary.com/v1_1/<cloud name>/image/upload” before running the example.

<script src="https://api.cloudinary.com/v1_1/<cloumn_name>/upload" type="text/javascript"></script>
<script src="https://api.cloudinary.com/v1_1/<cloumn_name>/delete_by_token" type="text/javascript"></script>

Step 2:

Add the following code to your .html file

<form id="file-form" method="post" enctype="multipart/form-data">
    Upload a File:
    <input type="file" id="myfile" name="myfile">
    <input type="submit" id="submit" name="submit" value="Upload File Now">
</form>

Step 3:

Add the following code to your .js file.

change your cloud name in the URL variable. and change your upload_preset name. To upload parent you have to go here

$('#submit').on('click', function () {
        debugger
        const url = "https://api.cloudinary.com/v1_1/<cloud_name>/upload";
        const form = document.querySelector("form");

        form.addEventListener("submit", (e) => {
            e.preventDefault();

            const files = document.querySelector("[type=file]").files;
            const formData = new FormData();

            for (let i = 0; i < files.length; i++) {
                debugger
                let file = files[i];
                formData.append("file", file);
                formData.append("upload_preset", "f1wv9aon");

                fetch(url, {
                    method: "POST",
                    body: formData
                })
                    .then((response) => {
                        console.log(response)
                        return response.text();
                    })
                    .then((data) => {
                        console.log(data);
                        document.getElementById("data").innerHTML += data;
                    });
            }
        });
    })

After that, you can check your image in the media library

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories