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

How to Make Boomerang Video Effect With Cloudinary

When you see the term boomerang, what is the first thing that comes to mind?

A thrown tool made of wood that returns to its thrower? Another definition is reversal, logically portraying the aim of the tool itself. Based on this definition, the term boomerang videos” came into play to depict videos that loop back and forth.

Read more
Shortening the Development Cycle of Media-Related apps with Cloudinary

Currently, the Android platform boasts the highest demand for mobile solutions, as evidenced by Google’s announcement in 2017 that there were two billion monthly active Android devices, a number that is likely to increase in the years ahead. For app developers like you, now is the right time to build and release solutions for Android. you might have also noticed that a higher percentage of apps being developed nowadays are filled with visual media: images and videos.

Read more
Build Your Own Image Storyboard Android App

Globally, approximately two billion people now own smartphones, which also feature cameras capable of capturing photos and videos of a tonal richness and quality unimaginable even five years ago. Until recently, those cameras behaved mostly as optical sensors, catching light that determines the resulting image's pixels. The next generation of cameras, however, can blend hardware and computer-vision algorithms that apply to an image's semantic content, spawning creative mobile photo and video apps.

Read more
Cloudinary Delivers Simplified Image Management Workflow for Fairfax Media's Digital Transformation

Fairfax Media Limited [ASX:FXJ] is one of the largest media companies in Australia and New Zealand that engages audiences and communities via print and digital media. It includes recognizable mastheads including The Australian Financial Review, The Sydney Morning Herald and The Age. Fairfax Media operates numerous news and information websites, as well as tablet and smartphone apps, for online news sites.

Read more
Bleacher Report Scores with Real-Time Video Highlights Delivered by Cloudinary

Bleacher Report is a global digital destination for sports fans, creating and collaborating on content at the intersection of sports and culture. Owned by Turner, a division of Time Warner, Bleacher Report's website and social channels focus on sports culture for the next generation of fans. Bleacher Report also has a five-star mobile app and popular email newsletters, which are part of the company’s strategy for instantly delivering in-depth articles, results and video highlights personalized for users’ favorite teams, players and leagues.

Read more