Cloudinary Blog

AJAX File Upload - Quick Tutorial & Time Saving Tips

By Prosper Otemuyiwa
AJAX File Upload - Quick Tutorial & Time Saving Tips

File upload through AJAX techniques can be daunting because of the large amount of code, let alone the painstaking tasks involved, such as the following:

  • Setting up an XMLHttpRequest instance
  • Setting up various handlers on the XMLHttpRequest object
  • Setting up a back end to accept data from the AJAX request
  • Validating the form
  • Setting up an efficient feedback loop for the audience

No sweat, however, thanks to Cloudinary, a cloud-based, end-to-end media-management solution that automates and streamlines the workflow for media assets, including images, videos, and audios. Specifically, Cloudinary selects, uploads, analyzes, manipulates, optimizes, and delivers those assets across devices in short order. Be sure to sign up for a FREE Cloudinary account and try this for yourself.

This article describes how to upload AJAX files with Cloudinary with only a few lines of code and no need for any of the above tasks.

Preliminary Steps

As a first step, create a free Cloudinary account, which includes a dashboard, a unique cloud name for you, an API key, and an API secret, which you’ll need to work with Cloudinary.

Subsequently, create an upload preset, which defines the options that apply to all your uploads.

Direct Ajax File Uploads With Cloudinary

Follow these three simple steps:

Create an HTML form.

In your root directory, create an HTML form (an index.html file) with the following code, which contains the fields for file uploads:

index.html

Copy to clipboard
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX File Uploads 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>

You now have a form with the following elements:

  • An input field and a submit button.
  • An action attribute—within the form tag—that points to the script that handles the upload.
  • A method attribute that specifies the operation post undertaken by this form.
  • An enctype attribute, whose value specifies the content type of the upload. Here, because the task in question is to upload files, do not specify the enctype attribute.
  • An id attribute for both input fields, which handle the form elements with JavaScript.

Add the Cloudinary JavaScript library.

JavaScript plugins on Cloudinary facilitate image uploads to its server. Include them in your index.html file, like this:

Copy to clipboard
 <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>

Specify Direct Uploads

Create a file called fileUpload.js with the following in the root directory:

Copy to clipboard
$(function() {
    // Configure Cloudinary
    // with the credentials on
    // your Cloudinary 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"/>';
}

Note
Be sure to replace the YOUR_CLOUD_NAME, YOUR_UPLOAD_PRESET, and YOUR_API_KEY variables with their values from your Cloudinary dashboard.

Ajax File Uploads to a Backend Server

To handle file uploads with AJAX and store the files on a backend server (e,g PHP Server), create an HTML form and two upload scripts: one written in JavaScript and the other in PHP.:

HTML form In your root directory, build an HTML form (an index.html file) with the following code, which contains the fields for file uploads:

Copy to clipboard
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Uploads With AJAX</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>

Note the following:

  • The form contains an input field and a submit button.
    • 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 post.
    • An enctype attribute, whose value specifies the content type of the upload. Here, because the task in question is to upload files, do not specify the enctype attribute.
    • An id attribute for both input fields, which handles the form elements with JavaScript.

AJAX-enabled script in JavaScript

In your root directory, create a file called fileUpload.js with the following code:

Copy to clipboard
(function(){
    var form = document.getElementById('file-form');
    var fileSelect = document.getElementById('myfile');
    var uploadButton = document.getElementById('submit');
    var statusDiv = document.getElementById('status');

    form.onsubmit = function(event) {
        event.preventDefault();

        statusDiv.innerHTML = 'Uploading . . . ';

        // Get the files from the input
        var files = fileSelect.files;

        // Create a FormData object.
        var formData = new FormData();

        //Grab only one file since this script disallows multiple file uploads.
        var file = files[0]; 

        //Check the file type.
        if (!file.type.match('image.*')) {
            statusDiv.innerHTML = 'You cannot upload this file because it’s not an image.';
            return;
        }

        if (file.size >= 2000000 ) {
            statusDiv.innerHTML = 'You cannot upload this file because its size exceeds the maximum limit of 2 MB.';
            return;
        }

         // Add the file to the AJAX request.
        formData.append('myfile', file, file.name);

        // Set up the request.
        var xhr = new XMLHttpRequest();

        // Open the connection.
        xhr.open('POST', '/fileUpload.php', true);


        // Set up a handler for when the task for the request is complete.
        xhr.onload = function () {
          if (xhr.status === 200) {
            statusDiv.innerHTML = 'Your upload is successful..';
          } else {
            statusDiv.innerHTML = 'An error occurred during the upload. Try again.';
          }
        };

        // Send the data.
        xhr.send(formData);
    }
})();

Step by step, the process proceeds as follows:

Grab all the elements, i.e., the form, the file-input, and status div, as reflected in this code:

Copy to clipboard
    var form = document.getElementById('file-form');
    var fileSelect = document.getElementById('myfile');
    var statusDiv = document.getElementById('status');

Call the form’s onsubmit event. After the user has submitted the form, attach an event handler to the form:

Copy to clipboard
form.onsubmit = function(event) {
.

}

Get hold of the file specified by the user and, for a robust experience, keep that user informed of what’s transpiring behind the scenes, like this:

Copy to clipboard
.

 statusDiv.innerHTML = 'Uploading . . . ';

  // Picking up files from the input .  .  .
  var files = fileSelect.files;

 // Uploading only one file; multiple uploads are not allowed.
  var file = files[0]; 

...

Create a form object, validate the size and type of the file to be uploaded, and add the file to form, like this:

Copy to clipboard
        // Create a FormData object.
        var formData = new FormData();


        //Check the file type.
        if (!file.type.match('image.*')) {
            statusDiv.innerHTML = ''You cannot upload this file because its not an image.';
            return;
        }

        if (file.size >= 2000000 ) {
            statusDiv.innerHTML = 'You cannot upload this file because its size exceeds the maximum limit of 2 MB.';
            return;
        }

         // Add the file to the request.
        formData.append('myfile', file, file.name);

Set up an AJAX request, open a connection, and listen for the onload event of the xhr object.

Copy to clipboard

// Set up an AJAX request.
        var xhr = new XMLHttpRequest();

        // Open the connection.
        xhr.open('POST', '/fileUpload.php', true);


        // Set up a handler for when the task for the request is complete.
        xhr.onload = function () {
          if (xhr.status === 200) {
            statusDiv.innerHTML = Your upload is successful.';
          } else {
            statusDiv.innerHTML = 'An error occurred while uploading the file...Try again';
          }
        };

        // Send the Data.
        xhr.send(formData);

Here, you make a post request to fileUpload.php. And yes, you must still process the file on the back end, to which the AJAX request submits the file for processing.

Before leveraging the preceding code for production, you must make provisions for several edge cases, for example, perform checks to ensure that only safe files are posted to your back end.

PHP script

Below is the script written in PHP.

Copy to clipboard
<?php
    $currentDir = getcwd();
    $uploadDirectory = "/uploads/";

    $errors = []; // Store all foreseen and unforeseen errors here.

    $fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions.

    $fileName = $_FILES['myfile']['name'];
    $fileSize = $_FILES['myfile']['size'];
    $fileTmpName  = $_FILES['myfile']['tmp_name'];
    $fileType = $_FILES['myfile']['type'];
    $fileExtension = strtolower(end(explode('.',$fileName)));

    $uploadPath = $currentDir . $uploadDirectory . basename($fileName); 

    echo $uploadPath;

    if (isset($fileName)) {

        if (! in_array($fileExtension,$fileExtensions)) {
            $errors[] = "This process does not support this file type. Upload a JPEG or PNG file only.";
        }

        if ($fileSize > 2000000) {
            $errors[] = "You cannot upload this file because its size exceeds the maximum limit of 2 MB.";
        }

        if (empty($errors)) {
            $didUpload = move_uploaded_file($fileTmpName, $uploadPath);

            if ($didUpload) {
                echo "The file " . basename($fileName) . " has been uploaded.";
            } else {
                echo "An error occurred. Try again or contact your system administrator.";
            }
        } else {
            foreach ($errors as $error) {
                echo $error . "These are the errors" . "\n";
            }
        }
    }


?>

Note
Ensure you are running a PHP server, such as this one:

PHP server

Now when you run that PHP app, it looks like this: run application

In addition, note the following:

  • The PHP script works for image files only.
  • The file-size limit is a file 2 MB.

Upload images to a dedicated file server in addition to the server in which your web app resides. Check out this source code for a related tutorial.

Conclusion

Uploading AJAX files with Cloudinary is a cakewalk. Even though mastering AJAX technologies could be challenging, you can take advantage of them readily with the Cloudinary library for your app. Give it a try: signing up for Cloudinary is free.


Want to Learn More About File Uploads?

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more