Mental Jetsam

By Peter Finch

Archive for January, 2013

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) {
                evt.stopPropagation();
                evt.preventDefault();
            };
            $(this).bind("dragenter", noopHandler);
            $(this).bind("dragexit", noopHandler);
            $(this).bind("dragover", noopHandler);
            $(this).bind("drop", function (devt) {
                noopHandler(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 = revt.target.result;
                        if (settings.preview) settings.preview(file, data64);
                        if (settings.url && settings.filename && settings.data) {
                            var postdata = {} ;
                            postdata[settings.filename] = file.name ;
                            postdata[settings.data] = data64 ;
                            $.ajax({
                                url : settings.url,
                                type : "POST",
                                data : postdata
                            }) ; 
                        }
                    };
                    reader.readAsDataURL(file);
                });
            });
        });
    }
})(jQuery);

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 () {
    $("#dropbox").html5Upload({
        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>
<div id="preview" ></div>
Advertisements

Posted in Uncategorized | Leave a Comment »