Demo

Try it out yourself!

Source

Fork me on github!

How it works

Dropbox hover styling

First we assign the hover-styles, so the dropbox lights up upon mouseover and actual dragover.

var dropbox = $(".dropbox");

// dropbox hover styling
dropbox.mouseover(function() {
    $(this).addClass("dropbox-hover");
    $(this).removeClass("dropbox-error");
}).mouseout(function() {
    $(this).removeClass("dropbox-hover");
    $(this).removeClass("dropbox-error");
});

dropbox.bind('dragenter', function() {
    $(this).addClass("dropbox-hover");
    $(this).removeClass("dropbox-error");
    return false;
});

The drop

Now we bind the drop-event and check if dropped files are actually images. If not, add the dropbox-error class, so the dropbox lights up to indicate this error. When all is well, the list of files is passed to add_data_urls().

// the actual drop
dropbox.bind('drop', function(e) {
    var event = e.originalEvent;
    var data = event.dataTransfer;
    var files = data.files;

    // check files for image type
    var imageType = /image.*/;
    for(var i=0; i<files.length; i++) {
        if (!files[i].type.match(imageType)) {
            $(this).toggleClass("dropbox-error", 1000 );
            return false;
        }
    }

    // we have all the files we need
    add_data_urls(files);

    return false;
});

FileReader

Using the FileReader api we can read the content of the dropped files and show the data in the textarea.

// extract data url and add them to the list
function add_data_urls(files) {
    // target
    var data_urls = $("#dataurls");

    // poor-man's jquery templates
    var div = $("<div />", {
            className: "data_url",
        }),
        h4 =  $("<h4 />"),
        img = $("<img />"),
        text = $("<textarea />");

    for(var i=0; i<files.length; i++) {
        var reader = new FileReader();

        // add this file to the list on-screen
        var thumb = img.clone();
        var txt = text.clone();

        var d = div.clone()
            .append(thumb)
            .append(h4.clone()
            .text(files[i].fileName))
            .append(txt);

        d.appendTo(data_urls);

        // when the data is loaded, display the image and put the data in the textbox
        reader.onload = (function(image, textarea) {
            return function(e) {
            var data = e.target.result;
            image.attr('src', data);
            textarea.val(data);
            }
        })(thumb, txt);

        // read it!
        reader.readAsDataURL(files[i]);
    }
}
blog comments powered by Disqus