如何从文件夹中读取文件

时间:2016-04-24 17:33:51

标签: javascript webkit fileapi

发现这篇文章展示了如何区分文件上传和目录jsfiddle,但它们没有解释我如何处理目录上传。难以找到任何例子。任何人都知道如何获取目录中每个文件的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
    }
  }
};

2 个答案:

答案 0 :(得分:1)

对文件夹使用DirectoryReader directoryEntry.createReader()readEntries(),对单个或多个文件丢弃使用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);
        })
      })
    }
  }
}

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

答案 1 :(得分:0)

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

最后,您可以使用Ajax

将formData提交给服务器