Event.dataTransfer.files vs. event.dataTransfer.items

I am playing with the drag and drop API and there are two ways to collect files from DragEvent.dataTransfer

, there are readonly files: FileList

and readonly items: DataTransferItemList

.

Seems to be items

a superset files

, collecting File[]

from is items

more complex and also items

not supported in older IE, so files

it is easier to work with and has better support.However, the article on MDN first uses items

, and only when not supported, switch to files

.

My question is, if I only need to build a collection File[]

from DragEvent

, can I use the property dataTransfer.files

or does it dataTransfer.items

have any advantages that are worth it?

Self-answer:

In modern browser (chrome) the collection is files

empty. The file being dragged is only available via items

, so you can't rely on the files

.

+9


source to share


2 answers


I also haven't found a proper explanation of the difference between the two APIs. But after experimenting with this API, I found it to be dataTransfer.items

much newer and defined to provide not only file deletion, but also a drag and drop functionality (i.e. when you want to drag an element from your page to another part of your page). And since I don't care about old IE, I only use dataTransfer.items

.



+1


source


The main difference between dataTransfer.items

and dataTransfer.files

is that it dataTransfer.items

also contains subdirectories.

This is important if you want to drag and drop subdirectories (for example, to load the entire directory tree with all the files in it)



Below is an example of how this can be done:

function DragAndDrop_Handler(e) {
    e.preventDefault();

    var items = e.dataTransfer.items;
    for (var i=0; i<items.length; i++) {        
        var item = items[i].webkitGetAsEntry();  //Might be renamed to GetAsEntry() in 2020
        if (item) {
            GetFileTree(item);
        }
    }
}


function GetFileTree(item, path) {
    path = path || "";
    if (item.isFile) {

        item.file(function(file) {
            console.log(file);
        });

    } else if (item.isDirectory) {

        console.log(item.fullPath);  //console.log(item.name)

        // Get folder contents  
        var dirReader = item.createReader();
        dirReader.readEntries(function(entries) {
            for (var i=0; i<entries.length; i++) {
                GetFileTree(entries[i], path + item.name + "/");
            }
        });
    }
}

      

0


source







All Articles