javascript tutorial - [Solved-5 Solutions] Upload files asynchronously - javascript - java script - javascript array



Problem:

How to upload a file asynchronously with jQuery ?

Solution 1:

  • With HTML5 we can make file uploads with Ajax and jQuery. Not only that, we can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently We had to make a file uploader, but we didn't want to use Flash nor Iframes or plugins and after some research we came up with the solution.
  • The HTML:
<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>
click below button to copy the code. By JavaScript tutorial team

First, we can do some validation if we want. For example, in the onChange event of the file:

$(':file').on('change', function() {
    var file = this.files[0];
    if (file.size > 1024) {
        alert('max upload size is 1k')
    }

    // Also see .name, .type
});
click below button to copy the code. By JavaScript tutorial team

Now the Ajax submit with the button's click:

$(':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
        // We *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;
        },
    });
});
click below button to copy the code. By JavaScript tutorial team
  • As we can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.

Solution 2:

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

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

Solution 3:

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

$(document).ready(function() {
    $("#uploadbutton").jsupload({
        action: "addFile.do",
        onComplete: function(response){
            alert( "server response: " + response);
        }
    });
click below button to copy the code. By JavaScript tutorial team

Solution 4:

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 we use, or where they are on the page

-- Use as little as --

$('#one-specific-file').ajaxfileupload({
  'action': '/upload.php'
});
click below button to copy the code. By JavaScript tutorial team

-- or as much as --

$('#one-specific-file').ajaxfileupload({
  'action': '/upload.php'
});

click below button to copy the code. By JavaScript tutorial team

Solution 5:

We can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
    // Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        // Handle file upload complete
    }
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Upload files asynchronously