Is it possible to update FileList?

后端 未结 2 1119
广开言路
广开言路 2020-11-28 10:20

I have:


Every time the user selects a file(s), I build a list o

相关标签:
2条回答
  • 2020-11-28 10:52

    You can't modify a Filelist, but you can create a new one using a DataTransfer object, and if you wish you can copy your data into it to create a duplicate with the specific change you want to make.

    let list = new DataTransfer();
    let file = new File(["content"], "filename.jpg");
    list.items.add(file);
    
    let myFileList = list.files;
    

    You can then set it as the file attribute of the DOM node:

    fileInput.files = myFileList;
    

    If you wished, you could iterate over your old FileList, copying files to the new one.

    0 讨论(0)
  • 2020-11-28 10:54

    It's like you said

    you can only set the files with a FileList, unfortunately the FileList is not constructable or changeable, but there is a way to get one in a round about way

    /**
     * @params {array} files List of file items
     * @return FileList
     */
    function FileListItems (files) {
      var b = new ClipboardEvent("").clipboardData || new DataTransfer()
      for (var i = 0, len = files.length; i<len; i++) b.items.add(files[i])
      return b.files
    }
    
    var files = [
      new File(['content'], 'sample1.txt'),
      new File(['abc'], 'sample2.txt')
    ];
    
    
    fileInput.files = new FileListItems(files)
    console.log(fileInput.files)
    <input type="file" id="fileInput" multiple />

    doing this will trigger a change event, so you might want to toggle the change event listener on and off

    0 讨论(0)
提交回复
热议问题