HTML5 drag and drop folder detection in firefox. Is it even possible?

后端 未结 3 1218
情书的邮戳
情书的邮戳 2020-11-30 09:21

I have a drop zone where I want to detect whether the dragged item is a folder or file. In chrome I achieved this by using

for (var i = 0; i < nrOfFiles;          


        
3条回答
  •  一整个雨季
    2020-11-30 09:42

    Here's what I did to solve this problem:

    var files = [];
    
    for( var i = 0; i < e.dataTransfer.files.length; i++ ){
        var ent = e.dataTransfer.files[i];
        if( ent.type ) {
            // has a mimetype, definitely a file
            files.push( ent );
        } else {
            // no mimetype:  might be an unknown file or a directory, check
            try {
                // attempt to access the first few bytes of the file, will throw an exception if a directory
                new FileReader().readAsBinaryString( ent.slice( 0, 5 ) ); 
                // no exception, a file
                files.push( ent );
            } catch( e ) {
                // could not access contents, is a directory, skip
            }
        }
    }
    

    Basically:

    • If the drag-and-drop entry has a mime type, then it is a file
    • Otherwise, try to read the entry contents
      • Only read the first 5 bytes (to avoid loading large files into memory by accident): ent.slice( 0, 5 )
      • If the read succeeds, then it is a file
      • If the read fails, then this is a directory

    Enjoy!

提交回复
热议问题