Rectangle 27 325

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 317

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 317

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 317

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 317

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 317

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 317

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 316

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.

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

The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload

For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.

Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.

JQuery File Uploader

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2265

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2210

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2208

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2208

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2208

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2207

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2207

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 2206

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.

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

First, you can do some validation if you 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
});

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
        // 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;
        },
    });
});

As you 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.

Can I then use $_FILES in the upload.php?

This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)

Doesn't work in IE7-9

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

It's FormData who does all the magic here. Be sure to check these docs it covers all your question about multiple files and fields.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 165

You can easily determine the file MIME type with JavaScript's FileReader before uploading it to a server. I agree that we should prefer server-side checking over client-side, but client-side checking is still possible. I'll show you how and provide a working demo at the bottom.

Check that your browser supports both File and Blob. All major ones should.

if (window.FileReader && window.Blob) {
    // All the File APIs are supported.
} else {
    // File and Blob are not supported
}

You can retrieve the File information from an <input> element like this (ref):

<input type="file" id="your-files" multiple>
<script>
var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {
    // When the control has changed, there are new files
    var files = control.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }
}, false);
</script>

Here is a drag-and-drop version of the above (ref):

<div id="your-files"></div>
<script>
var target = document.getElementById("your-files");
target.addEventListener("dragover", function(event) {
    event.preventDefault();
}, false);

target.addEventListener("drop", function(event) {
    // Cancel default actions
    event.preventDefault();
    var files = event.dataTransfer.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }
}, false);
</script>

We can now inspect the files and tease out headers and MIME types.

You can navely ask Blob for the MIME type of whatever file it represents using this pattern:

For images, MIME types come back like the following:

Caveat: The MIME type is detected from the file extension and can be fooled or spoofed. One can rename a .jpg to a .png and the MIME type will be be reported as image/png.

To get the bonafide MIME type of a client-side file we can go a step further and inspect the first few bytes of the given file to compare against so-called magic numbers. Be warned that it's not entirely straightforward because, for instance, JPEG has a few "magic numbers". This is because the format has evolved since 1991. You might get away with checking only the first two bytes, but I prefer checking at least 4 bytes to reduce false positives.

Here is the essential code to retrieve the file header:

var blob = files[i]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
  var header = "";
  for(var i = 0; i < arr.length; i++) {
     header += arr[i].toString(16);
  }
  console.log(header);

  // Check the file signature against known types

};
fileReader.readAsArrayBuffer(blob);

You can then determine the real MIME type like so (more file signatures here and here):

switch (header) {
    case "89504e47":
        type = "image/png";
        break;
    case "47494638":
        type = "image/gif";
        break;
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
        type = "image/jpeg";
        break;
    default:
        type = "unknown"; // Or you can use the blob.type as fallback
        break;
}

Accept or reject file uploads as you like based on the MIME types expected.

Here is a working demo for local files and remote files (I had to bypass CORS just for this demo). Open the snippet, run it, and you should see three remote images of different types displayed. At the top you can select a local image or data file, and the file signature and/or MIME type will be displayed.

Notice that even if an image is renamed, its true MIME type can be determined. See below.

// Return the first few bytes of the file as a hex string
function getBLOBFileHeader(url, blob, callback) {
  var fileReader = new FileReader();
  fileReader.onloadend = function(e) {
    var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
    var header = "";
    for (var i = 0; i < arr.length; i++) {
      header += arr[i].toString(16);
    }
    callback(url, header);
  };
  fileReader.readAsArrayBuffer(blob);
}

function getRemoteFileHeader(url, callback) {
  var xhr = new XMLHttpRequest();
  // Bypass CORS for this demo - naughty, Drakes
  xhr.open('GET', '//cors-anywhere.herokuapp.com/' + url);
  xhr.responseType = "blob";
  xhr.onload = function() {
    callback(url, xhr.response);
  };
  xhr.onerror = function() {
    alert('A network error occurred!');
  };
  xhr.send();
}

function headerCallback(url, headerString) {
  printHeaderInfo(url, headerString);
}

function remoteCallback(url, blob) {
  printImage(blob);
  getBLOBFileHeader(url, blob, headerCallback);
}

function printImage(blob) {
  // Add this image to the document body for proof of GET success
  var fr = new FileReader();
  fr.onloadend = function() {
    $("hr").after($("<img>").attr("src", fr.result))
      .after($("<div>").text("Blob MIME type: " + blob.type));
  };
  fr.readAsDataURL(blob);
}

// Add more from http://en.wikipedia.org/wiki/List_of_file_signatures
function mimeType(headerString) {
  switch (headerString) {
    case "89504e47":
      type = "image/png";
      break;
    case "47494638":
      type = "image/gif";
      break;
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
      type = "image/jpeg";
      break;
    default:
      type = "unknown";
      break;
  }
  return type;
}

function printHeaderInfo(url, headerString) {
  $("hr").after($("<div>").text("Real MIME type: " + mimeType(headerString)))
    .after($("<div>").text("File header: 0x" + headerString))
    .after($("<div>").text(url));
}

/* Demo driver code */

var imageURLsArray = ["http://media2.giphy.com/media/8KrhxtEsrdhD2/giphy.gif", "http://upload.wikimedia.org/wikipedia/commons/e/e9/Felis_silvestris_silvestris_small_gradual_decrease_of_quality.png", "http://static.giantbomb.com/uploads/scale_small/0/316/520157-apple_logo_dec07.jpg"];

// Check for FileReader support
if (window.FileReader && window.Blob) {
  // Load all the remote images from the urls array
  for (var i = 0; i < imageURLsArray.length; i++) {
    getRemoteFileHeader(imageURLsArray[i], remoteCallback);
  }

  /* Handle local files */
  $("input").on('change', function(event) {
    var file = event.target.files[0];
    if (file.size >= 2 * 1024 * 1024) {
      alert("File size must be at most 2MB");
      return;
    }
    remoteCallback(escape(file.name), file);
  });

} else {
  // File and Blob are not supported
  $("hr").after( $("<div>").text("It seems your browser doesn't support FileReader") );
} /* Drakes, 2015 */
img {
  max-height: 200px
}
div {
  height: 26px;
  font: Arial;
  font-size: 12pt
}
form {
  height: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
  <input type="file" />
  <div>Choose an image to see its file signature.</div>
</form>
<hr/>
fileReader.readAsArrayBuffer(blob.slice(0,4))
for(var i = 0; i < bytes.length; i++) { var byte = bytes[i]; fileSignature += (byte < 10 ? "0" : "") + byte.toString(16); }

@drakes where did you get file signature ffd8ffe2? Based on the wiki link you gave the file signatures for jpeg are ffd8ffdb, ffd8ffe0, and ffd8ffe1. Can you confirm? Thanks

@Deadpool See here. There are more, less common, JPEG formats from different makers. For example, FF D8 FF E2 = CANNON EOS JPEG FILE, FF D8 FF E3 = SAMSUNG D500 JPEG FILE. The key part of the JPEG signature is only 2 bytes, but to reduce false positives I added the most common 4-byte signatures. I hope that helps.

It looks like FF D8 FF is consistent in JPEG files. I think its safe to assume that only JPEG files have the pattern. It would be difficult to keep track of the 4-byte signature especially when some of the signatures are manufacturer dependent. Thanks @Drakes !

html5 - How to check file MIME type with javascript before upload? - S...

javascript html5 file-upload mime-types
Rectangle 27 11

Not sure why you want to do this... but if you where resizing before uploading I just found out this http://www.plupload.com/ it does all the magic for you in any imaginable method.

Unfortunatelly HTML5 resize only is suported with Mozilla borwser, but you can redirect other browsers to flash and silverlight.

I was using http://swfupload.org/ in flash, it does the job very well, but the resize size is very small. (cannot remember the limit) and does not go back to html4 when flash is not available.

It's nice to do client-side resizing for when a user tries to upload a 10mb photo that is only going to be stored as a much smaller photo. It'll upload much quicker this way.

Same scenario here, as soon as you have a file input and the user is on a smartphone and snaps an image using the camera, its going to be around 10 mb on modern smartphones. If you on the server side anyway are resizing it and only storing a much smaller version of it, you'll save a lot of cellular data and loading time in doing the resizing beforehand in the client.

Image resizing client-side with JavaScript before upload to the server...

javascript image resize client-side
Rectangle 27 34

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" />
</form>

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

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
  • [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 )

$('body').iDownloader({
     "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 love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload
Rectangle 27 31

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" />
</form>

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

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
  • [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 )

$('body').iDownloader({
     "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 love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload