Handle directory/files upload with one input javascript

ぃ、小莉子 提交于 2019-12-05 08:08:12

问题


I want to allow users dragging and uploading directory and files.

i know i could create

<input type="file" multiple />
<!-- for files/multiple files upload-->

and

<input type="file" directory mozDirectory webkitDirectory />
<!-- for directory uploads -->

i tried detecting while user is dragging the item if it is a directory or file and setting directory attribute depending on that, but turns out that javascript doesn't allow you to check that.

also i have seen on lot of websites that users are able to drag both files and directories together and even multiple directories.

how can i achieve that?


回答1:


Dragging and droppping of folders is available in Chrome >= 21

Here's what you need (Not tried, but it can give you the idea):

function traverseFileTree(item, path) {
  path = path || "";
  if (item.isFile) {
    // Get file
    item.file(function(file) {
      console.log("File:", path + file.name);
    });
  } else if (item.isDirectory) {
    // Get folder contents
    var dirReader = item.createReader();
    dirReader.readEntries(function(entries) {
      for (var i=0; i<entries.length; i++) {
        traverseFileTree(entries[i], path + item.name + "/");
      }
    });
  }
}

dropArea.addEventListener("drop", function(event) {
  event.preventDefault();

  var items = event.dataTransfer.items;
  for (var i=0; i<items.length; i++) {
    // webkitGetAsEntry is where the magic happens
    var item = items[i].webkitGetAsEntry();
    if (item) {
      traverseFileTree(item);
    }
  }
}, false);

More information can be found here

Answer taken from here



来源:https://stackoverflow.com/questions/30049276/handle-directory-files-upload-with-one-input-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!