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

Hipcamp Optimizes Images and Improves Page Load Times With Cloudinary

When creating a website that allows campers to discover great destinations, Hipcamp put a strong emphasis on featuring high-quality images that showcased the list of beautiful locations, regardless of whether users accessed the site on a desktop, tablet, or phone. Since 2015, Hipcamp has relied on Cloudinary’s image management solution to automate cropping and image optimization, enabling instant public delivery of photos, automatic tagging based on content recognition, and faster loading of webpages. In addition, Hipcamp was able to maintain the high standards it holds for the look and feel of its website.

Read more
New Image File Format: FUIF: Why Do We Need a New Image Format

In my last post, I introduced FUIF, a new, free, and universal image format I’ve created. In this post and other follow-up pieces, I will explain the why, what, and how of FUIF.

Even though JPEG is still the most widely-used image file format on the web, it has limitations, especially the subset of the format that has been implemented in browsers and that has, therefore, become the de facto standard. Because JPEG has a relatively verbose header, it cannot be used (at least not as is) for low-quality image placeholders (LQIP), for which you need a budget of a few hundred bytes. JPEG cannot encode alpha channels (transparency); it is restricted to 8 bits per channel; and its entropy coding is no longer state of the art. Also, JPEG is not fully “responsive by design.” There is no easy way to find a file’s truncation offsets and it is limited to a 1:8 downscale (the DC coefficients). If you want to use the same file for an 8K UHD display (7,680 pixels wide) and for a smart watch (320 pixels wide), 1:8 is not enough. And finally, JPEG does not work well with nonphotographic images and cannot do fully lossless compression.

Read more
 New Image File Format: FUIF:Lossy, Lossless, and Free

I've been working to create a new image format, which I'm calling FUIF, or Free Universal Image Format. That’s a rather pretentious name, I know. But I couldn’t call it the Free Lossy Image Format (FLIF) because that acronym is not available any more (see below) and FUIF can do lossless, too, so it wouldn’t be accurate either.

Read more