Cloudinary Blog

AJAX File Upload with Cloudinary in Five Minutes

AJAX File Upload - The Easy Way

TLDR Web applications have improved greatly. Gone are the days where you click a button and wait for an endless reload of your browser to get the desired results. Modern applications take advantage of AJAX (Asynchronous Javascript and XML) to cut in half the time taken from a click-to-action to response-from-server to give users a seamless experience navigating their platforms.

Handling an AJAX file upload task can be very daunting because it involves a lot of code and checks, such as:

  • Setting up an XMLHttpRequest instance
  • Setting up various handlers on the XMLHttpRequest object
  • Setting up a backend to accept data from the AJAX request
  • Form validation
  • Setting up an efficient feedback loop to the user

However, I’ll show you how to perform an AJAX file upload using Cloudinary with just a few lines of code and without having to execute all the tasks I mentioned above.

Cloudinary is a cloud-based, end-to-end media management solution. As a critical part of the developer stack, Cloudinary automates and streamlines your entire media asset workflow. It handles a variety of media, from images, video and audio to emerging media types. It also automates every stage of the media management lifecycle, including media selection, upload, analysis and administration, manipulation, optimization and delivery.

What are we waiting for? Let’s get started on how to upload images with PHP using Cloudinary!

Create a FREE Cloudinary Account

A Cloudinary account, Cloudinary Dashboard, your cloud name, API Key and API Secret are all required to interact with Cloudinary functionalities.

After you set up a Cloudinary account, you can create an upload preset. Upload presets enable you to centrally define a set of image upload options, instead of specifying them in each upload call. We will use the preset when making an upload request.

  1. Create A HTML Form

    You need to build up a HTML form that will contain the fields the user will interact with to upload a file. Create an index.html file in your root directory and the following code:

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>AJAX File Upload With Cloudinary</title>
    </head>
    <body>
    <form id="file-form" action="fileUpload.php" 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>
    <p id="status"></p>
    <script type="text/javascript" src="fileUpload.js"></script>
    </body>
    </html>

    In the code above, we have a form with one input field and a submit button. Now, the form tag has an action attribute that points to the script that will take care of the actual upload process. It also has a method attribute that specifies the kind of operation this form will undertake, which is a POST action.

    The value of the enctype attribute is very important. It determines the content type that the form submits. If we were not dealing with file uploads, then we would not specify the enctype attribute on the form in most cases.

    The two fields also have an id attribute. This attribute will enable us to handle the form elements with JavaScript.

  2. Fetch the Cloudinary JS library

    Cloudinary provides JavaScript plugins that make image upload to the Cloudinary server very easy. Include them in your index.html file like so:

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

    Create a file in the root directory, fileUpload.js and this code to it:

    $(function() {
    // Configure Cloudinary
    // with credentials available on
    // your Cloudinary account dashboard
    $.cloudinary.config({ cloud_name: 'YOUR_CLOUD_NAME', api_key: 'YOUR_API_KEY'});
    // Upload button
    var uploadButton = $('#submit');
    // Upload button event
    uploadButton.on('click', function(e){
        // Initiate upload
        cloudinary.openUploadWidget({ cloud_name: 'YOUR_CLOUD_NAME', upload_preset: 'YOUR_UPLOAD_PRESET', tags: ['cgal']}, 
        function(error, result) { 
            if(error) console.log(error);
            // If NO error, log image data to console
            var id = result[0].public_id;
            console.log(processImage(id));
        });
    });
    })
    function processImage(id) {
    var options = {
        client_hints: true,
    };
    return '<img src="'+ $.cloudinary.url(id, options) +'" style="width: 100%; height: auto"/>';
    }

    It’s that simple. Make sure you replace your cloudname, uploadpreset and api_key with the right values from your Cloudinary dashboard.

Conclusion

We have successfully covered how to handle AJAX file uploads with Cloudinary in a very short time. Five minutes? I think it may have even been less than that. Implementation of AJAX can be very tricky, but with the Cloudinary library, you can implement it easily in your application. Try Cloudinary for free today!

Additional Resources:

Recent Blog Posts

Integrating Cloudinary with Forestry’s Media Library

At Forestry, we believe that there is a bright future for static HTML sites built with tools like Jekyll and Hugo. These tools can create sites that run well, and are easy to host and maintain, because they don’t require any server-side code.

Read more
Video Optimization With the HTML5 <video> Player

Lack of experience and compression knowhow can cause significant user-experience problems. For instance, on a major retail site, I recently ran into a 48 MB video-hero banner. Pulling out the video and encoding it as an H.264 MP4 reduces the size to 1.9 MB. So, despite the desire for more video content, developers have not yet caught up to best practices. How do we get the best of both worlds without creating a disaster like the one above?

Read more
Build a Facial Emotion Recognition Based Video Suggestion App

Developers are always looking for new and creative ways to deliver content that resonates with the way users feel. Often using the latest technical innovations the market has to offer such as Artificial Intelligence (AI) and Machine Learning (ML). What better way to demonstrate innovative uses of these technology in a consumer market than capturing expressions from your users and then serving content based on that expression!

Read more
Improve Customer Data Protection with GDPR Implementation

TL;DR

Yay! We've done it! Gold-Star for us! We've talked with all the people, made all the changes, paid all the lawyers and checked all the boxes. GDPR? ✅Done!

Not so fast. Of course, conforming to the GDPR regulations introduced in Europe is just the beginning. This is a process and a state of mind that must become part of our long-term cultural ethos.

Read more
Magento Image and Video Optimization

As the number of channels and devices continues to grow, it is becoming much more challenging to deliver an optimal visual experience. On an eCommerce site, engagement and conversions are critical. Factors such as page load time strongly influence search engine rankings, shopping experiences, conversion rates and, ultimately, your revenue. An optimized visual experience positively affects conversion rates. But it also can introduce resource bottlenecks, as every image and video needs to be delivered in the most efficient format, quality and resolution, based on the viewing device.

Read more