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

10 Website Videos Mistakes and How to Solve Them

It should come as no surprise that video use on the internet is exploding. You can see the dramatic growth of video on the average site in this SpeedCurve blog post.

With the growth in video comes greater bandwidth use, which is not only costly for your IT budget, but for your visitors as well. Beyond the expense, there is the user experience to consider. The heavier the page, the longer it will take to load, and the greater likelihood visitors will abandon your site. Page load speed is also an important factor in SEO ranking, so clearly video is something we need to take seriously and get right. Video is challenging, presenting terms still unfamiliar to developers - like codecs, bitrate and adaptive bitrate streaming. As a result, mistakes are being made in video implementation.

Read more
Android Data Saver: Optimizing Mobile Data Usage with Cloudinary

Over the life of a mobile device, the cost of a cellular data plan often exceeds that of the device itself. To optimize data usage and purge useless data on their mobile devices, users can enable Data Saver from Android 7.0 (API level 24). To do so, users toggle Data Saver in quick settings under the Notification shade or under Settings > Data usage. With Data Saver enabled, apps that aren't whitelisted cannot use cellular data in the background. They are also directed to consume less data while active.

Read more
Introducing the Cloudinary Upload Widget v2

At Cloudinary, we manage the entire pipeline of media assets for thousands of customers of varying sizes from numerous verticals. Cloudinary is an end-to-end solution for all your image and video needs, including upload, storage, administration, manipulation, optimization and dynamic delivery.

Read more
Convert an Image to a 3D Canvas With Cloudinary

Note
This post was cowritten with Daniel Mendoza.
Note
This post was cowritten with Daniel Mendoza.
Note

Famed American poet Henry David Thoreau once said, “This world is but a canvas to our imagination.” And, like your imagination, the transformations you can apply to images with Cloudinary are practically endless. You can even render any flat image to appear three-dimensional and framed on a canvas.

Read more
Mobile Optimization: Optimize Your Mobile-Web User Experience

TL;DR

We live in a visual world, often while on the go, and consumers expect media-rich web content. Accordingly, the loading speed of images and videos is a big factor in user experience. To optimize customer satisfaction with your mobile content, you must focus on the quality, format, and size of your digital assets. With Cloudinary, optimization is simple, not only enhancing your mobile web and app performance, but also upping your SEO game and boosting customer experience.

Read more