Categories
JavaScript Answers

How to get the filename from a file input with JavaScript?

Spread the love

Sometimes, we want to get the filename from a file input with JavaScript.

In this article, we’ll look at how to get the filename from a file input with JavaScript.

How to get the filename from a file input with JavaScript?

To get the filename from a file input with JavaScript, we can can it from the files property.

For instance, we write:

<input type='file'>

to add a file input.

Then we write:

const input = document.querySelector("input")
input.onchange = (e) => {
  const [file] = e.target.files
  console.log(file.name)
}

to select the input with querySelector.

Then we set input.onchange to a function that gets the selected files from e.target.files.

And then we get the file from the files object and get the file name from file.name.

Conclusion

To get the filename from a file input with JavaScript, we can can it from the files property.

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 *