【问题标题】:Removing elements from dropped FileList从删除的 FileList 中删除元素
【发布时间】:2013-02-14 16:59:50
【问题描述】:

我有一个处理我页面上拖放文件的函数:

function createDropHandlers() {
  var target = document;
  if (target === null) {
    return false;
  }

  // attach the 'dragover' event to the container
  target.addEventListener('dragover', function(event) {
    event.preventDefault();
  }, true);

  // attach the 'drop' event to the container
  target.addEventListener('drop', function(event) {
    event.preventDefault();
    var files = event.dataTransfer.files;

    // if (files.length > 3)
    // do something like
    // files.slice(files.length-3, files.length);

    for (var i = 0; i < files.length; i++) {
        processFile(files[i]);
        // ...
    }
  }, true);
}

我想做的是在我的for 循环之前(以及在以任何方式“处理”文件之前)检查是否拖动了 3 个以上的文件,如果是,只需将“数组”切片到最后3个元素。我知道FileList 是只读的,所以我不确定我有什么选择可以实现这一目标...
我不会上传文件,并且在“处理”它们之后,我将不再需要 File 对象。我需要做的就是检查文件是否为音频文件,从中读取一些元数据并在页面上显示元数据。

【问题讨论】:

    标签: javascript jquery html file filelist


    【解决方案1】:

    slice() 是来自 Array 原型的方法。虽然它返回一个新数组,但它可能不在 FileList 原型中。您可以使用 Array.prototype.slice 方法并将其应用于文件列表:

    Array.prototype.slice.call( fileList ); //will return an array-copy of the filelist
    Array.prototype.slice.call( fileList, 0, 3 ); //Then simply use the slice arguments at your convenience
    

    您也可以在参数上使用(并且经常在 js-libraries 代码中看到)这个技巧。请注意, slice 不会像 splice() 那样修改原始对象。

    您可以查看 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice#Array-like 以获取 MDN 上的说明。

    【讨论】:

      猜你喜欢
      • 2011-03-09
      • 2017-12-29
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 2018-12-04
      • 2013-07-09
      • 2012-10-07
      • 2018-07-03
      相关资源
      最近更新 更多