使用 webkitGetAsEntry 的 Javascript 拖放文件上传问题

标签 javascript html file-upload

Example JSFiddle here

上面的 fiddle 是我的代码的精简版本,只是为了突出问题(尝试将文件拖放到窗口中)。基本上,webkitGetAsEntry().file() 不允许我写入其范围之外的任何内容,但是,如果您拖动文件然后手动执行 console.log(fileList)(但是,jsfiddle 阻止了这个)它工作正常。任何帮助将不胜感激,谢谢!

上传.js

function Upload() {
_this = this;
this.fileList = 'no file';

this.fire = function(droppedFiles) {
    for(i = 0; i< droppedFiles.length; i++) {
        this.buildFileSource(droppedFiles[i].webkitGetAsEntry());
    }
    //This returns the original string
    console.log(this.fileList);
}

this.buildFileSource = function(item, path) {
    if(item.isFile) {
        item.file(function(file) {
            _this.fileList = 'file';
            //This works as expected
            console.log(_this.fileList);
        } );
    }
};
}

//Event listeners for dragging  
$(document).ready(function() {
    window.addEventListener("dragenter", function(e) {
            event.stopPropagation();
            event.preventDefault();
            return false;
        }, false);
        window.addEventListener("dragover", function(e) {
            event.stopPropagation();
            event.preventDefault();
            return false;
        }, false);
        window.addEventListener("dragleave", function(e) {
            event.stopPropagation();
            event.preventDefault();
            return false;
        }, false);

    window.addEventListener("drop", function(e) {
        e.stopPropagation();
        e.preventDefault();

        upload = new Upload;
        upload.fire(e.dataTransfer.items);
        return false;
    }, false);
});

最佳答案

console.log(_this.fileList); 在你的 fire 函数被调用之前 fileList 中被修改buildFileSource 方法。这是因为 FileEntry(您的 item 变量)上的 file 函数是异步函数。实际上,对 buildFileSource 的每次调用也是异步的。在 MDN 上查找有关 Entry 接口(interface)及其两个子接口(interface)的更多详细信息:FileEntryDirectoryEntry

请注意,使用 webkitGetAsEntry 方法意味着您的代码只能在 Chrome 21+ 上运行,因为此方法非常特定于 Chrome(由于前缀)和底层概念( Entry 对象)属于Filesystem API,目前只有Chrome 21+支持。

关于使用 webkitGetAsEntry 的 Javascript 拖放文件上传问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17007659/

相关文章:

javascript - 带有图像的下拉菜单(没有像 jquery 这样的库)

javascript - React/Router/MemoryRouter - 如何传递历史属性并在子组件中使用 push()?

javascript - JSON API 中货币的最佳格式/类型是什么

javascript - 在 ES6 类构造函数中工作

javascript - 是否可以将 Template7 代码放在单独的文件而不是 html 中

php - 上传多个文件 - 通知 : Array to string conversion in

php - Blueimp jQuery 文件上传,传递额外的表单数据

python - 上传文件时错误请求(400),Flask

javascript - 在 React 中的表上创建可扩展行的简单方法是什么?

html - 在没有 javascript 的情况下以不同的方向显示图像,但只有 html 和 css