upload file asynchronously in javascript

How to Upload File Asynchronously in JavaScript

Often you may need to upload file asynchronously from a web page, or allow your website visitors to do the same. If you upload file using simple form submission, it will freeze your browser till upload finishes and also refresh the page once it is over. This is not desirable so it is general practice to upload files asynchronously. In this article, we will learn how to upload file asynchronously in JavaScript.


How to Upload File Asynchronously in JavaScript

The following steps are applicable in most modern browsers such as Chrome & Firefox that support HTML5, which provides several easy to use, out of the box methods to upload files & data to browsers.

HTML5 allows you to easily upload files using AJAX and JQuery. It also allows you to perform file validations as well as display upload progress using progress tag or div.

Let us say you have the following HTML5 form with a button to upload files. It has a browse button with text ‘Choose File’ to select the file and upload button to upload the selected file.

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

Now we write JavaScript code to validate files and then upload it. Here is a simple validation to check if uploaded file’s size is more than 1kb. It is triggered on file change event.

$(':file').on('change', function () {
  var file = this.files[0];

  if (file.size > 1024) {
    alert('max upload size is 1k');
  }

  // Also see .name, .type
});

Finally, here is the AJAX submit code that uploads the file. It is triggered when the upload button is clicked.

$(':button').on('click', function () {
  $.ajax({
    // Your server script to process the upload
    url: 'upload.php',
    type: 'POST',

    // Form data
    data: new FormData($('form')[0]),

    // Tell jQuery not to process data or worry about content-type
    // You *must* include these options!
    cache: false,
    contentType: false,
    processData: false,

    // Custom XMLHttpRequest
    xhr: function () {
      var myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        // For handling the progress of the upload
        myXhr.upload.addEventListener('progress', function (e) {
          if (e.lengthComputable) {
            $('progress').attr({
              value: e.loaded,
              max: e.total,
            });
          }
        }, false);
      }
      return myXhr;
    }
  });
});

The above code uploads the file to upload.php server side script. It basically reads file data from our file upload form and then calculates the file upload progress that you can display on browser to indicate upload status.

In this article, we have learnt how to upload files using HTML5 in web browsers. You can customize it as per your requirement.

Also read:

How to Store Data in Local Storage in JavaScript
How to Display Local Storage Data in JavaScript
How to Enable, Disable & Install Yum Plugins
How to Delete Root Mails in Linux
How to Check if Element is Visible in Viewport

Leave a Reply

Your email address will not be published. Required fields are marked *