Skip to content
This repository has been archived by the owner on May 25, 2023. It is now read-only.

Drag and drop uploads from another web page

Sebastian Tschan edited this page Jul 12, 2011 · 17 revisions

The following code snippet allows to upload images by drag&drop from another webpage, though this is currently only supported on Firefox:

$('#fileupload').fileupload().bind('drop', function (e) {
    var url = $(e.originalEvent.dataTransfer.getData('text/html')).filter('img').attr('src');
    if (url) {
        $.getImageData({
            url: url,
            success: function (img) {
                var canvas = document.createElement('canvas'),
                    file;
                canvas.getContext('2d').drawImage(img, 0, 0);
                if ($.type(canvas.mozGetAsFile) === 'function') {
                    file = canvas.mozGetAsFile('file.png');
                }
                if (file) {
                    $('#fileupload').fileupload('add', {files: [file]});
                }
            }
        });
    }
});

Due to the Same Origin policy, which also applies to the canvas element, it is not possible to load an image directly from another domain.
Therefore one of the requirements for the code snippet above is a server-side proxy to retrieve the image data: The $.getImageData library has to be included along with the jQuery File Upload libraries.

When the BlobBuilder interface becomes available, this might work for for Google Chrome and other browsers as well, see Convert Data URI to File then append to FormData.

Clone this wiki locally