最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Handle directoryfiles upload with one input javascript - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question asked May 5, 2015 at 9:35 user3870546user3870546
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论