HTML5 directory reader not working

2019-08-17 05:04发布

问题:

I have this code, but when I select a directory and then try to read from it, it always gives me empty array even when there is files in it. Does anyone know what is wrong?

Thanks

<input type="file" id="filepicker" name="fileList" webkitdirectory directory />
<button id="ff">Read</button>
<ul id="filelist"></ul>

js

function toArray(list) {
  return Array.prototype.slice.call(list || [], 0);
}

function listResults(entries) {
  // Document fragments can improve performance since they're only appended
  // to the DOM once. Only one browser reflow occurs.
  var fragment = document.createDocumentFragment();

  entries.forEach(function(entry, i) {
    var img = entry.isDirectory ? '<img src="folder-icon.gif">' :
                                  '<img src="file-icon.gif">';
    var li = document.createElement('li');
    li.innerHTML = [img, '<span>', entry.name, '</span>'].join('');
    fragment.appendChild(li);
  });

  document.querySelector('#filelist').appendChild(fragment);
}

function onInitFs(fs) {

  var dirReader = fs.root.createReader();
  var entries = [];

  // Call the reader.readEntries() until no more results are returned.
  var readEntries = function() {
     dirReader.readEntries (function(results) {
      if (!results.length) {
        listResults(entries.sort());
      } else {
        entries = entries.concat(toArray(results));
        readEntries();
      }
    }, errorHandler);
  };

  readEntries(); // Start reading dirs.

}

function errorHandler(e) {
  var msg = '';

  switch (e.code) {
    case DOMError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case DOMError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case DOMError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case DOMError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case DOMError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}



document.getElementById("ff").addEventListener("click", function() {
    var selectedFiledf = $("#filepicker").val();
    window.webkitRequestFileSystem(selectedFiledf, 1024*1024, onInitFs, errorHandler);
});