How to work with FileList (from <input type=“file”>) in Javascript?

前端 未结 3 789
心在旅途
心在旅途 2020-12-11 07:24

In this W3schools example, console.log on the input element reveals a FileInput object:

FileList {0: File, 1: File, length: 2}

相关标签:
3条回答
  • 2020-12-11 08:04

    It is not possible to add File objects to FileList. You can use FormData to append Files to a single object.

    var data = new FormData();
    document.querySelector("input[type=file]")
    .addEventListener("change", function(event) {
      for (var i = 0, files = event.target.files; i < files.length; i++) {
        data.append("file-" + [...data.keys()].length, files[i], files[i].name)
      }
    })
    
    0 讨论(0)
  • 2020-12-11 08:13

    An array is fine for holding onto the File instances, but FormData is better if you want to upload them somewhere. If you want to log out or view the FormData, turning it into a Map is an option. Keep in mind that FormData is iterable.

    var formData = new FormData();
    var index = 0;
    
    function onDrop(event)
    {
      var dt = event.dataTransfer;
      var files = dt.files;
    
      var count = files.length;
      output("File Count: " + count + "\n");
    
      for (var i = 0; i < files.length; i++) {    
        formData.append(files[i].name, files[i]);
      }
    }
    
    function output(text)
    {
      document.getElementById("output").textContent += text;
      console.dir(new Map(formData));
    }
    

    See this JSBin.

    0 讨论(0)
  • 2020-12-11 08:20

    Untested, but this should work

    var fileStore = [];
    
    function myFunction(){
        var txt = "";
        if ('files' in x) {
            if (x.files.length == 0) {
                txt = "Select one or more files.";
            } else {
                fileStore.push.apply(fileStore,x.files);
                console.log(x.files);
                console.log(fileStore);
    

    More on Function::apply

    More on Array::push

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