Categories
JavaScript Answers

How to Extract Filename of the Selected File from an HTML File Input Control with JavaScript?

Spread the love

We can get the file’s name with the name property.

For instance, if we have the following HTML:

<input type='file'>

Then we can listen for file selection and get the name of the selected file by writing:

const input = document.querySelector('input');
input.addEventListener('change', (e) => {
  const [file] = e.target.files;
  console.log(file.name)
})

We get the file input with document.querySelector .

Then we call addEventListener on it to listen to the change event.

In the event handler function, we get the first file selected from e.target.files and assign it to the file variable.

And then we get the name of the selected file with file.name .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *