Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get filename on html javascript jquery drag/drop event (non html5)

I am trying to get the filename(s) when someone drags a file or files from their local computer to a div.

The purpose is to upload images by dragging and dropping without the use of html5 Drag and Drop API (to support older browsers).

How can I get the filename(s) from a jquery drop event on a div when someone drags and drops a file (or files)?

like image 225
iedoc Avatar asked Jan 09 '23 01:01

iedoc


1 Answers

I've found plenty on how to do this in html5, and after searching through the event variable in the browser debugger, i was able to find exactly what i was looking for.

I just have to say this was far more simple than i thought it would have been considering i spent at least an hour looking for a solution on the net.

What you have to do is get the "originalEvent" from the jquery event, which will have a dataTransfer attribute. The dataTransfer attribute contains an array of files, which you can iterate though (if they exist), and get the name attribute of each file (along with lastModified, lastModifiedDate, size, and type.

the code needed to get the name of the first file from the drop was: e.originalEvent.dataTransfer.files[0].name

you can get the length of the file array by:

e.originalEvent.dataTransfer.files.length

so just an example, to iterate through the files that were dragged and dropped onto the dive, you could do:

for (var i = 0; i < e.originalEvent.dataTransfer.files.length; i++) {
    alert(e.originalEvent.dataTransfer.files[i].name);
}

To get the "drop" event to fire, i needed to "cancel out" the dragover, dragenter, and dragleave events of the div (dragover may not have to be canceled out?)

heres my solution:

html code:

<div id="dropimagebox" class="noselect">Drop image here or click</div>

javascript code:

function initDragAndDropDialog()
{           
    document.getElementById("imagedialog").showModal();

    $("#dialoginnerds").bind('clickoutside',function(){
            document.getElementById("imagedialog").close();
    });
    $("#dialoginnerds").on("dragover", function(e) {
        e.preventDefault();  
        e.stopPropagation();
        $("#dropimagebox").addClass('dragging');
    });
    $('#dialoginnerds').on('dragenter',function(e){
        e.preventDefault();
        e.stopPropagation();
        $("#dropimagebox").addClass('dragging');
    })
    $('#dialoginnerds').on('dragleave',function(e){
        e.preventDefault();
        e.stopPropagation();
        $("#dropimagebox").removeClass('dragging');
    })

    $("#dialoginnerds").on('drop', function (e) {
        e.preventDefault();
        alert(e.originalEvent.dataTransfer.files[0].name);
    });
}
like image 77
iedoc Avatar answered Jan 10 '23 18:01

iedoc