[Javascript] How can I upload files asynchronously?


There are various ready-made plugins on doing file upload for jQuery.

Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.

Here's few:

You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.


I would like to upload a file asynchronously with jQuery. This is my HTML:

<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>

And here my Jquery code:

$(document).ready(function () {
    $("#uploadbutton").click(function () {
        var filename = $("#file").val();

            type: "POST",
            url: "addFile.do",
            enctype: 'multipart/form-data',
            data: {
                file: filename
            success: function () {
                alert("Data Uploaded: ");

Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?

Current Solution

I am using the jQuery Form Plugin to upload files.

You can upload simply with jQuery .ajax().


<form id="upload-form">
        <label for="file">File:</label>
        <input type="file" id="file" name="file" />
        <progress class="progress" value="0" max="100"></progress>
    <hr />
    <input type="submit" value="Submit" />


.progress { display: none; }


$(document).ready(function(ev) {
    $("#upload-form").on('submit', (function(ev) {
            xhr: function() {
                var progress = $('.progress'),
                    xhr = $.ajaxSettings.xhr();


                xhr.upload.onprogress = function(ev) {
                    if (ev.lengthComputable) {
                        var percentComplete = parseInt((ev.loaded / ev.total) * 100);
                        if (percentComplete === 100) {

                return xhr;
            url: 'upload.php',
            type: 'POST',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            success: function(data, status, xhr) {
                // ...
            error: function(xhr, status, error) {
                // ...

I recommend using the Fine Uploader plugin for this purpose. Your JavaScript code would be:

$(document).ready(function() {
    action: "addFile.do",
    onComplete: function(response){
      alert( "server response: " + response);

jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.

    'swf': '/public/js/uploadify.swf',
    'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
    'cancelImg': '/public/images/uploadify-cancel.png',
    'multi': true,
    'onQueueComplete': function (queueData) {
        // ...
    'onUploadStart': function (file) {
        // ...

I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:

$(document).ready(function () {
    $('#btn_Upload').live('click', AjaxFileUpload);

function AjaxFileUpload() {
    var fileInput = document.getElementById("#Uploader");
    var file = fileInput.files[0];
    var fd = new FormData();
    fd.append("files", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'Uploader.ashx');
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
        else if (uploadResult == 'success')

This AJAX file upload jQuery plugin uploads the file somehwere, and passes the response to a callback, nothing else.

  • It does not depend on specific HTML, just give it a <input type="file">
  • It does not require your server to respond in any particular way
  • It does not matter how many files you use, or where they are on the page

-- Use as little as --

  'action': '/upload.php'

-- or as much as --

  'action': '/upload.php',
  'params': {
    'extra': 'info'
  'onComplete': function(response) {
    console.log('custom handler for file:');
  'onStart': function() {
    if(weWantedTo) return false; // cancels upload
  'onCancel': function() {
    console.log('no file selected');

var formData=new FormData();

    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    success:function(data){ }

You can use form data to post all your values including images.

Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder. Fiddle here

var reader = new FileReader();

        reader.onload = function(readerEvt) {
            var binaryString = readerEvt.target.result;
            document.getElementById("base64textarea").value = btoa(binaryString);


Then to retrieve:

window.open("data:application/octet-stream;base64," + base64);

I have been using the below script to upload images which happens to work fine.


<input id="file" type="file" name="file"/>
<div id="response"></div>


    var input = document.getElementById("file");
    var formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    input.addEventListener("change", function (evt) {
        var i = 0, len = this.files.length, img, reader, file;

        for ( ; i < len; i++ ) {
            file = this.files[i];

            if (!!file.type.match(/image.*/)) {
                if ( window.FileReader ) {
                    reader = new FileReader();
                    reader.onloadend = function (e) {
                        //showUploadedItem(e.target.result, file.fileName);

                if (formdata) {
                    formdata.append("image", file);

                if (formdata) {
                    jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');

                        url: "upload.php",
                        type: "POST",
                        data: formdata,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                         jQuery('div#response').html("Successfully uploaded");
                alert('Not a vaild image!');

    }, false);


I use response div to show the uploading animation and response after upload is done.

Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data as in the script.

At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST data.

Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.

Look for Handling the upload process for a file, asynchronously in here: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

Sample from the link

if (isset($_FILES['myFile'])) {
    // Example:
    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
?><!DOCTYPE html>
    <title>dnd binary upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        function sendFile(file) {
            var uri = "/index.php";
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // Handle response.
                    alert(xhr.responseText); // handle response.
            fd.append('myFile', file);
            // Initiate a multipart/form-data upload

        window.onload = function() {
            var dropzone = document.getElementById("dropzone");
            dropzone.ondragover = dropzone.ondragenter = function(event) {

            dropzone.ondrop = function(event) {

                var filesArray = event.dataTransfer.files;
                for (var i=0; i<filesArray.length; i++) {
        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>

It is an old question, but still has no answer correct answer, so:

Have you tried jQuery-File-Upload ?

Here is an example from the link above -> 1 that might solve your problem:

    add: function (e, data) {
        var that = this;
        $.getJSON('/example/url', function (result) {
            data.formData = result; // e.g. {id: 123}
                .options.add.call(that, e, data);

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.


var $bar   = $('.ProgressBar');
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';

  success: function(response) {
    // Response

I hope it would be helpful

The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.

That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...

<form target="iframe" action="" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />

<iframe name="iframe" id="iframe" style="display:none" ></iframe>

You can also read the contents of the iframe onLoad for server errors or success responses and then output that to user.

Chrome, iFrames, and onLoad

-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading

Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.

The only solution that I found works for Chrome was to use a cookie.

To do that basically when the upload/download is started:

  • [Client Side] Start an interval to look for the existence of a cookie
  • [Server Side] Do whatever you need to with the file data
  • [Server Side] Set cookie for client side interval
  • [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.

Using a cookie for this is ugly but it works.

I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here


The same basic principal applies to uploading, as well.

To use the downloader ( include the JS, obviously )

     "onComplete" : function(){
          $('#uiBlocker').css('display', 'none'); //hide ui blocker on complete

 $('somebuttion').click( function(){
      $('#uiBlocker').css('display', 'block'); //block the UI
      $('body').iDownloader('download', 'htttp://example.com/location/of/download');

And on the server side, just before transferring the file data, create the cookie

 setcookie('iDownloader', true, time() + 30, "/");

The plugin will see the cookie, and then trigger the onComplete callback.

I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.

The challenge is in getting AJAX upload working as the standard remote_form_for doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.

That's where the jQuery-form plugin comes into play.

Here’s the Rails code for it:

<% remote_form_for(:image_form, 
                   :url => { :controller => "blogs", :action => :create_asset }, 
                   :html => { :method => :post, 
                              :id => 'uploadForm', :multipart => true }) 
                                                                        do |f| %>
 Upload a file: <%= f.file_field :uploaded_data %>
<% end %>

Here’s the associated JavaScript:

$('#uploadForm input').change(function(){
  beforeSubmit: function(a,f,o) {
   o.dataType = 'json';
  complete: function(XMLHttpRequest, textStatus) {
   // XMLHttpRequest.responseText will contain the URL of the uploaded image.
   // Put it in an image element you create, or do with it what you will.
   // For example, if you have an image elemtn with id "my_image", then
   //  $('#my_image').attr('src', XMLHttpRequest.responseText);
   // Will set that image tag to display the uploaded image.

And here’s the Rails controller action, pretty vanilla:

 @image = Image.new(params[:image_form])
 render :text => @image.public_filename

I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.