'How do get the value of input element of type "file"

I have tried to solve this problem without success. I want to get the "value" of an input element of "type = file". I don't know what I am doing wrong that's preventing me from getting the "input value".

function addFile() {

  let toUpload = document.getElementById("fileid").click();
  console.log(toUpload.value);
  //Do something with file name;
}
<button class=" btn border border-1
  rounded-pill " id="add-btn" onclick="addFile()">
    <i class="bx bx-plus-medical">
    </i>
    Choose file                  
</button>

<input id='fileid' type='file' hidden/>

The file upload dialogue comes up. But I cannot access the file name. Who can figure out an issue with the above code please?



Solution 1:[1]

You have three different problems here.

  1. click() doesn't return the element, and the element has the value. Store the element in a variable and use that for reading and for clicking.
  2. You need to wait until the user picks a file before reading the value, currently you are trying to get the value before it has changed. Use an event listener.
  3. The value is an obfuscated path. Use the files property to get details of the files selected.

function addFile() {
  let toUpload = document.getElementById("fileid");
  toUpload.addEventListener('change', event => {
      //Do something with file name;
      console.log(toUpload.value);  
      console.log(toUpload.files[0].name);
  }, { once: true });
  toUpload.click();
}
<button class=" btn border border-1
  rounded-pill " id="add-btn" onclick="addFile()">
    <i class="bx bx-plus-medical">
    </i>
    Choose file                  
</button>

<input id='fileid' type='file' hidden/>

Solution 2:[2]

input type file doesn't have a value, it will have a property called files

files is an array of files (in case the input allows multiple), each file will have a property called name to get the display name

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin
Solution 2 Anas AL-zghoul