AJAX File Upload - Quick Tutorial and Time Saving Tips (original) (raw)

AJAX file upload is the process of uploading files from a local computer to a server. When a user selects a file in the browser and clicks the submit button, the browser copies the file from the local machine and sends it to the server. The server then saves the file to the specified location.

In this article, you’ll find:

The HTML form tag has an action attribute pointing to the script that will take care of the actual upload process. The form tag also has a method attribute that specifies the kind of operation this form will undertake, which is POST. AJAX uses the browser’s built-in XMLHttpRequest object to request data from the web server. It also uses JS and HTML DOM to use and display the data.

Web apps built using AJAX are efficient because they can quickly send and fetch data from the server without affecting the display of the existing page. Files can be uploaded to a backend server or directly to the cloud using a solution like Cloudinary.

There are the general steps for uploading a file using AJAX:

To make this process easier, you can use Cloudinary, a cloud-based, end-to-end media-management solution that can easily create, manage and deliver their digital experiences across any browser, device and bandwidth. Make sure you try this yourself, claim your free Cloudinary account now.

This article describes how easy it is to do an AJAX file upload with Cloudinary using only a few lines of code and no need for any of the above tasks.

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.

Follow these 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

`

AJAX File Uploads With Cloudinary Upload a File:

`Code language: HTML, XML (xml)

You now have a form with the following elements:

Add the Cloudinary JavaScript library.

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

 <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>

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

$(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"/>'; } Code language: JavaScript (javascript)

Note:

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

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 formIn your root directory, build an HTML form (an index.html file) with the following code, which contains the fields for file uploads:

`

File Uploads With AJAX Upload a File:
<p id="status"></p>
<script type="text/javascript" src="fileUpload.js"></script>

`Code language: HTML, XML (xml)

Note the following:

JavaScript AJAX File Upload Example

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

` (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);
}

})();

`Code language: JavaScript (javascript)

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:

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

`Code language: JavaScript (javascript)

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

`form.onsubmit = function(event) { ….

} `Code language: JavaScript (javascript)

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:

` ….

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];

...

`Code language: JavaScript (javascript)

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

` // 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 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 request.
    formData.append('myfile', file, file.name);

`Code language: PHP (php)

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

` … // 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);

`Code language: PHP (php)

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.

`<?php $currentDir = getcwd(); $uploadDirectory = "/uploads/";

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

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

<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mi>i</mi><mi>l</mi><mi>e</mi><mi>N</mi><mi>a</mi><mi>m</mi><mi>e</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">fileName = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.10903em;">N</span><span class="mord mathnormal">am</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>_FILES['myfile']['name'];
<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mi>i</mi><mi>l</mi><mi>e</mi><mi>S</mi><mi>i</mi><mi>z</mi><mi>e</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">fileSize = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.05764em;">S</span><span class="mord mathnormal">i</span><span class="mord mathnormal">ze</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>_FILES['myfile']['size'];
<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mi>i</mi><mi>l</mi><mi>e</mi><mi>T</mi><mi>m</mi><mi>p</mi><mi>N</mi><mi>a</mi><mi>m</mi><mi>e</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">fileTmpName  = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal">m</span><span class="mord mathnormal" style="margin-right:0.10903em;">pN</span><span class="mord mathnormal">am</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>_FILES['myfile']['tmp_name'];
<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mi>i</mi><mi>l</mi><mi>e</mi><mi>T</mi><mi>y</mi><mi>p</mi><mi>e</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">fileType = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.13889em;">T</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mord mathnormal">p</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>_FILES['myfile']['type'];
<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mi>i</mi><mi>l</mi><mi>e</mi><mi>E</mi><mi>x</mi><mi>t</mi><mi>e</mi><mi>n</mi><mi>s</mi><mi>i</mi><mi>o</mi><mi>n</mi><mo>=</mo><mi>s</mi><mi>t</mi><mi>r</mi><mi>t</mi><mi>o</mi><mi>l</mi><mi>o</mi><mi>w</mi><mi>e</mi><mi>r</mi><mo stretchy="false">(</mo><mi>e</mi><mi>n</mi><mi>d</mi><mo stretchy="false">(</mo><mi>e</mi><mi>x</mi><mi>p</mi><mi>l</mi><mi>o</mi><mi>d</mi><mi>e</mi><msup><mo stretchy="false">(</mo><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><msup><mi mathvariant="normal">.</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">fileExtension = strtolower(end(explode(&#x27;.&#x27;,</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.05764em;">E</span><span class="mord mathnormal">x</span><span class="mord mathnormal">t</span><span class="mord mathnormal">e</span><span class="mord mathnormal">n</span><span class="mord mathnormal">s</span><span class="mord mathnormal">i</span><span class="mord mathnormal">o</span><span class="mord mathnormal">n</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.0019em;vertical-align:-0.25em;"></span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">t</span><span class="mord mathnormal">o</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">o</span><span class="mord mathnormal" style="margin-right:0.02691em;">w</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mopen">(</span><span class="mord mathnormal">e</span><span class="mord mathnormal">n</span><span class="mord mathnormal">d</span><span class="mopen">(</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal" style="margin-right:0.01968em;">pl</span><span class="mord mathnormal">o</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mopen"><span class="mopen">(</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mord"><span class="mord">.</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mpunct">,</span></span></span></span>fileName)));

<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>u</mi><mi>p</mi><mi>l</mi><mi>o</mi><mi>a</mi><mi>d</mi><mi>P</mi><mi>a</mi><mi>t</mi><mi>h</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">uploadPath = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.01968em;">pl</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">h</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>currentDir . <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>u</mi><mi>p</mi><mi>l</mi><mi>o</mi><mi>a</mi><mi>d</mi><mi>D</mi><mi>i</mi><mi>r</mi><mi>e</mi><mi>c</mi><mi>t</mi><mi>o</mi><mi>r</mi><mi>y</mi><mi mathvariant="normal">.</mi><mi>b</mi><mi>a</mi><mi>s</mi><mi>e</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">uploadDirectory . basename(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">u</span><span class="mord mathnormal" style="margin-right:0.01968em;">pl</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">D</span><span class="mord mathnormal">i</span><span class="mord mathnormal">rec</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.03588em;">ory</span><span class="mord">.</span><span class="mord mathnormal">ba</span><span class="mord mathnormal">se</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span><span class="mopen">(</span></span></span></span>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)) {
        <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>d</mi><mi>i</mi><mi>d</mi><mi>U</mi><mi>p</mi><mi>l</mi><mi>o</mi><mi>a</mi><mi>d</mi><mo>=</mo><mi>m</mi><mi>o</mi><mi>v</mi><msub><mi>e</mi><mi>u</mi></msub><mi>p</mi><mi>l</mi><mi>o</mi><mi>a</mi><mi>d</mi><mi>e</mi><msub><mi>d</mi><mi>f</mi></msub><mi>i</mi><mi>l</mi><mi>e</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">didUpload = move_uploaded_file(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">d</span><span class="mord mathnormal">i</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.10903em;">U</span><span class="mord mathnormal" style="margin-right:0.01968em;">pl</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1.0361em;vertical-align:-0.2861em;"></span><span class="mord mathnormal">m</span><span class="mord mathnormal">o</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord"><span class="mord mathnormal">e</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">u</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.01968em;">pl</span><span class="mord mathnormal">o</span><span class="mord mathnormal">a</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span><span class="mord"><span class="mord mathnormal">d</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.10764em;">f</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.2861em;"><span></span></span></span></span></span></span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">e</span><span class="mopen">(</span></span></span></span>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";
        }
    }
}

?> `Code language: HTML, XML (xml)

Note:

Ensure you are running a PHP server:

Image of coding on a computer showing a php ajax file upload

Now when you run that PHP app, it looks like this:Image of php ajax file upload example

In addition, note the following:

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.

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.