Create multiple input type=“file” elements with their corresponding value (FileList) according to the main input type=“file” (multiple) element

后端 未结 1 1645
余生分开走
余生分开走 2020-12-12 00:36

I have this code where I loop unto files from a multiple input file type

1条回答
  •  悲哀的现实
    2020-12-12 01:29

    Yes, the requirement is possible. You will need to create a new FileList for each File object, then set .files property of the element to the FileList populated with the File object.

    The code at below returns the same results at Chromium 62+ and Firefox 57+, see comments by @Kaiido for evaluations at Safari and Edge.

    // FileList.js
    class FileList {
      constructor(...items) {
        // flatten rest parameter
        items = [].concat(...items);
        // check if every element of array is an instance of `File`
        if (items.length && !items.every(file => file instanceof File)) {
          throw new TypeError("expected argument to FileList is File or array of File objects");
        }
        // use `ClipboardEvent("").clipboardData` for Firefox, which returns `null` at Chromium
        // we just need the `DataTransfer` instance referenced by `.clipboardData`
        const dt = new ClipboardEvent("").clipboardData || new DataTransfer();
        // add `File` objects to `DataTransfer` `.items`
        for (let file of items) {
          dt.items.add(file)
        }
        return dt.files;
      }
    }
    
    document.querySelector("input[type=file]")
    .onchange = e => {
      for (let file of e.target.files) {
        const input = document.createElement("input");
        input.type = "file";
        input.files = new FileList(file);
        document.body.appendChild(input);
      }
    }

    // FileList.js
    function _FileList(items) {
        // flatten rest parameter
        items = [].concat.apply([], [items]);
        // check if every element of array is an instance of `File`
        if (items.length 
            && !items.every(function(file) { 
                 return file instanceof File})) {
          throw new TypeError("expected argument to FileList is File or array of File objects");
        }
        // use `ClipboardEvent("").clipboardData` for Firefox, which returns `null` at Chromium
        // we just need the `DataTransfer` instance referenced by `.clipboardData`
        var dt = new ClipboardEvent("").clipboardData || new DataTransfer();
        // add `File` objects to `DataTransfer` `.items`
        for (var i = 0; i < items.length; i++) {
          dt.items.add(items[i])
        }
        return dt.files;
    }
    
    document.querySelector("input[type=file]")
    .onchange = function(e) {
      for (var i = 0; i < e.target.files.length; i++) {
        var input = document.createElement("input");
        input.type = "file";
        input.files = new _FileList(e.target.files[i]);
        document.body.appendChild(input);
      }
    }

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