最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the filename of a dragged file (before drop) - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question asked Nov 20, 2020 at 22:08 skillmotionskillmotion 991 silver badge4 bronze badges 2
  • event.dataTransfer.files[n].type will contain the MIME type of the file being uploaded, e.g. image/png or text/plain, and event.dataTransfer.files[n].name will contain the file name. – Liftoff Commented Nov 20, 2020 at 22:13
  • 1 Thanks, but that's not working in the dragover event, only in the drop event and this is what i would like to avoid. – skillmotion Commented Nov 20, 2020 at 22:19
Add a ment  | 

1 Answer 1

Reset to default 9

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 patibility 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>

发布评论

评论列表(0)

  1. 暂无评论