4

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)?

1 Answer 1

9

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);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.