skillmotion
skillmotion

Reputation: 99

How to get the filename of a dragged file (before drop)

I would like to get the file extension of a file that is dragged from outside the browser. Looking through many tutorials and questions/answers on StackOverflow I just don't seem to find the answer (or I'm just to stupid to search the correct terms).

I know that you can access the filename within the ondrop event, but I want to react depending on the file type the user is dragging into my application before he drops the file. There's has to be some way, because Webflow (a web app to build responsive websites) is doing just that. Depending on the file type it gives you a different type of element.

I'm thankful for every little lead in the right direction

Upvotes: 5

Views: 2677

Answers (1)

Liftoff
Liftoff

Reputation: 25372

If you want it during the dragover event, your only option is the MIME type, which can be retrieved with event.dataTransfer.items[n].type. The rest of the file's information is inaccessible until the drop event.

Be aware of browser compatibility for this feature, as Internet Explorer and Safari both don't support this.

var dropReceiver = document.getElementById("dropReceiver");

dropReceiver.addEventListener('dragover', function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
    
    for(var i = 0; i < e.dataTransfer.items.length; i++)
    {
        console.log(e.dataTransfer.items[i].type);
    }
});
#dropReceiver
{
padding: 100px 120px;
background: blue;
color: white;
font-size: 30px;
text-align: center;
}
<div id="dropReceiver">Drag On Me</div>

Upvotes: 9

Related Questions