如何从文件夹中读取文件

How to read files from folder

发现这篇文章展示了如何区分文件上传和目录 How to handle dropped folders 但他们没有解释我如何处理目录上传。很难找到任何例子。有人知道如何获取目录中每个文件的 File 实例吗?

从那篇文章复制:

<div id=”dropzone”></div>


var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(e) {
  var length = e.dataTransfer.items.length;
  for (var i = 0; i < length; i++) {
    var entry = e.dataTransfer.items[i].webkitGetAsEntry();
    if (entry.isFile) {
      ... // do whatever you want
    } else if (entry.isDirectory) {
      ... // do whatever you want
    }
  }
};

从磁盘中拖出一些文件后。此 event.dataTransfer.file 是您的 fileList 对象。 你可以创建一个 formData 然后 将fileList中的文件一个一个添加到formData中。

最后你可以使用 Ajax

将 formData 提交到服务器

使用 DirectoryReader directoryEntry.createReader() , readEntries() for folders or , FileEntry file() 来放置单个或多个文件。

html

<div id="dropzone" 
     ondragenter="event.stopPropagation(); event.preventDefault();" 
     ondragover="event.stopPropagation(); event.preventDefault();" 
     ondrop="event.stopPropagation(); event.preventDefault(); handleDrop(event);">
    Drop files
</div>

javascript

function handleFiles(file) {
  console.log(file);
  // do stuff with `File` having `type` including `image`
  if (/image/.test(file.type)) {
    var img = new Image;
    img.onload = function() {
      var figure = document.createElement("figure");
      var figcaption = document.createElement("figcaption");
      figcaption.innerHTML = file.name;
      figure.appendChild(figcaption);
      figure.appendChild(this);
      document.body.appendChild(figure);
      URL.revokeObjectURL(url);
    }
    var url = URL.createObjectURL(file);
    img.src = url;
  } else {
    console.log(file.type)
  }
}

function handleDrop(event) {
  var dt = event.dataTransfer;
  var files = dt.files;
  var length = event.dataTransfer.items.length;
  for (var i = 0; i < length; i++) {
    var entry = dt.items[i].webkitGetAsEntry();
    if (entry.isFile) {
      // do whatever you want
      console.log("isFile", entry.isFile);
      entry.file(handleFiles);
    } else if (entry.isDirectory) {
      // do whatever you want
      console.log("isDirectory", entry.isDirectory);
      var reader = entry.createReader();
      reader.readEntries(function(entries) {
        entries.forEach(function(dir, key) {
          dir.file(handleFiles);
        })
      })
    }
  }
}

plnkrhttp://plnkr.co/edit/eGAnbA?p=preview