HTML5、JavaScript:从外部窗口拖放文件(Windows 资源管理器)

2022-01-11 00:00:00 drag-and-drop draggable javascript html

我能否提供一个很好的HTML5 文件拖放 实现示例?如果从外部应用程序(Windows 资源管理器)拖放到浏览器窗口,源代码应该可以工作.它应该适用于尽可能多的浏览器.

Can I kindly ask for a good working example of HTML5 File Drag and Drop implementation? The source code should work if drag and drop is performed from external application(Windows Explorer) to browser window. It should work on as many browsers as possible.

我想索要一个有很好解释的示例代码.我不想使用第三方库,因为我需要根据自己的需要修改代码.代码应基于 HTML5 和 JavaScript.我不想使用 JQuery.

I would like to ask for a sample code with good explanation. I do not wish to use third party libraries, as I will need to modify the code according to my needs. The code should be based on HTML5 and JavaScript. I do not wish to use JQuery.

我花了一整天的时间寻找好的材料来源,但令人惊讶的是,我没有找到任何好的材料.我发现的示例适用于 Mozilla,但不适用于 Chrome.

I spent the whole day searching for good source of material, but surprisingly, I did not find anything good. The examples I found worked for Mozilla but did not work for Chrome.

推荐答案

这是一个非常简单的例子.它显示一个红色方块.如果您将图像拖到红色方块上,它会将其附加到正文中.我已经确认它适用于 IE11、Chrome 38 和 Firefox 32.请参阅 Html5Rocks 文章以获得更详细的解释.

Here is a dead-simple example. It shows a red square. If you drag an image over the red square it appends it to the body. I've confirmed it works in IE11, Chrome 38, and Firefox 32. See the Html5Rocks article for a more detailed explanation.

var dropZone = document.getElementById('dropZone');

// Optional.   Show the copy icon when dragging over.  Seems to only work for chrome.
dropZone.addEventListener('dragover', function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
});

// Get file data on drop
dropZone.addEventListener('drop', function(e) {
    e.stopPropagation();
    e.preventDefault();
    var files = e.dataTransfer.files; // Array of all files

    for (var i=0, file; file=files[i]; i++) {
        if (file.type.match(/image.*/)) {
            var reader = new FileReader();

            reader.onload = function(e2) {
                // finished reading file data.
                var img = document.createElement('img');
                img.src= e2.target.result;
                document.body.appendChild(img);
            }

            reader.readAsDataURL(file); // start reading the file data.
        }
    }
});

<div id="dropZone" style="width: 100px; height: 100px; background-color: red"></div>

相关文章