上传文件夹(使用FileSystem API)

时间:2017-10-22 18:34:54

标签: javascript html drag-and-drop

我正在尝试使用FileSystem API上传文件夹。

dropzone.ondrop = function(e) {
                e.preventDefault();
                let items=e.dataTransfer.items;
                let formdata=new FormData();
                function scanFiles(item){
                    console.log("In scanFiles")
                    if (item.isFile) {
                        console.log("Typecasting...");

                        item.file(function(file) {
                            console.log(file);
                            formdata.append('directory',file);
                        });
                    }
                    else if (item.isDirectory) {
                        console.log("Directory...")
                        let directoryReader = item.createReader();
                        directoryReader.readEntries(function(entries) {
                            entries.forEach(function(entry) {
                                scanFiles(entry);
                            });
                        });
                    }
                }
                for (let i=0; i<items.length; i++) {
                    let item = items[i].webkitGetAsEntry();
                    console.log(item);
                    if (item) {
                        console.log("Calling scan");
                        scanFiles(item);
                        console.log("Ending scan");
                    }
                }

                var xhr=new XMLHttpRequest();
                xhr.open('post','uploadFolder/');
                xhr.send(formdata);
            }

基本上,代码所做的是获取一个删除的文件夹,读取其内容,如果是文件,将其作为文件输入附加到表单,并将其发送到所需的URL以进行进一步处理。 好吧,问题是当我运行它时,控制台输出是

FileSystemFileEntry { isFile: true, isDirectory: false, name: "Test.o", fullPath: "/Test.o", filesystem: FileSystem }  
Calling scan  
In scanFiles  
Typecasting...  
Ending scan  
File { name: "Test.o", lastModified: 1506856693000, lastModifiedDate: Date 2017-10-01T11:18:13.000Z, webkitRelativePath: "", size: 6240, type: "" }

在脚本中的所有行都已执行后创建文件对象,因此向该URL发送了错误的请求。

我想这是由于file()函数的闭包性质。有人可以告诉我如何以正确的方式输入文件?

1 个答案:

答案 0 :(得分:1)

.file()函数是异步的。您可以使用Promise构造函数和Promise.all()等待对.file()的所有调用,另请参阅How to upload and list directories at firefox and chrome/chromium using change and drop events

HTML

<input type="file" webkitdirectory>

的JavaScript

var dropzone = document.querySelector("input[type=file]");

dropzone.ondrop = function(e) {
  e.preventDefault();
  let items = e.dataTransfer.items;
  let formdata = new FormData();

  function scanFiles(item, index) {
    return new Promise(function(resolve) {
      if (item.isFile) {
        console.log("Typecasting...", item);

        item.file(function(file) {
          console.log(file, "here");
          formdata.append('file-' + index, file);
          resolve();
        });
      } else if (item.isDirectory) {
        console.log("Directory...")
        let directoryReader = item.createReader();

        directoryReader.readEntries(function(entries) {
          Promise.all(entries.map(scanFiles)).then(resolve);
        });
      }
    })
  }

  var p = Promise.all(Array.from(items, item => scanFiles(item.webkitGetAsEntry())));
  p.then(function() {
    // do stuff with `formdata` here
    for (let prop of formdata) {
      console.log(prop[0], prop[1])
    }
    /*
      var xhr=new XMLHttpRequest();
      formdata.append('address','');
      xhr.open('post','uploadFolder/');
      xhr.send(formdata);
    */
  })

}

jsfiddle https://jsfiddle.net/t03bvbzu/