Mental Jetsam

By Peter Finch

Simple HTML5 Drag, Drop and upload JQuery plugin

Posted by pcfinch on January 21, 2013

The following code is based on an excellect description of working with HTML5’s ability to handle drag and drop and auto upload items to a server, found at HTML5 Drag and Drop Upload and File API Tutorial. The code below implements this as a very simple JQuery plugin and current this only works on Chrome and Firefox.

(function ($) {
    $.fn.html5Upload = function (options) {
        var settings = $.extend({
            'start': function () { },
            'preview': function () { },
            'url': null,
            'data': 'data',
            'filename': 'filename'
        }, options);
        this.each(function () {
            function noopHandler(evt) {
            $(this).bind("dragenter", noopHandler);
            $(this).bind("dragexit", noopHandler);
            $(this).bind("dragover", noopHandler);
            $(this).bind("drop", function (devt) {
                var files = devt.originalEvent.dataTransfer.files;
                if (settings.start) settings.start();
                $.each(files, function (index, file) {
                    var reader = new FileReader();
                    reader.onload = function (revt) {
                        var data64 =;
                        if (settings.preview) settings.preview(file, data64);
                        if (settings.url && settings.filename && {
                            var postdata = {} ;
                            postdata[settings.filename] = ;
                            postdata[] = data64 ;
                                url : settings.url,
                                type : "POST",
                                data : postdata
                            }) ; 

You can use the following javascript to start the plugin. The “upload.aspx” script will be called and the filename and data will be passed to it in the “filename” and “data” post parameters.

$(document).ready(function () {
        start: function() {
            $("#preview").empty() ;
        preview: function (file, data64) {
            $("#preview").append($("<img>").attr("src", data64));
        url : "upload.ashx"

Some example HTML, just for good measure…

<div id="dropbox">
<span id="droplabel">Drop file here...</span>
<div id="preview" ></div>

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: