在 svelte 中过滤文件

Filtering files in svelte

最近我在 stack overlflow 上关注了一些关于在 svelte 中导入一些文件的帖子,这是代码:

<script>

    let files = [];
    
    function contentArray(ev){
        files = [...files, ...ev.target.files.filter(f => !files.includes(f))]
    }
    </script>
    
    
    <input type='file' multiple on:change={contentArray} accept=".txt">
    {#each files as file}
        <p>The imported file is: {file.name}</p>
    {#await file.text() then text}
        <pre>{text}</pre>
    {/await}
    {/each}

我的目标是当我导入一个文件时,如果我再次尝试导入它,程序根本不显示它。我尝试使用 filter 方法,但它给了我这个错误:

ev.target.files.filter is not a function or its return variable is not iterable

我在网上搜索了一下,但我不明白我哪里错了。 提前致谢。

ev.target.files 不是数组而是 FileList (FileList docs on MDN),因此没有 filter() 方法。

因此,要使用 filter(),您必须先将 FileList 转换为数组,您可以这样做:

let arrayFileList = [...ev.target.files];

// now you can arrayFileList.filter(...)

此外,根据您的设置,在您执行 !files.includes(f) 时比较 File 对象可能不会给您想要的结果。因此,您可能仍会多次得到同一个文件。这是因为将同一个文件多次添加到您的 <input type="file"> 时,对应的 File 实例可能不相同。因此,您可能希望根据

中的名称进行比较
arrayFileList.filter(f => !files.some(ff => ff.name === f.name));