Categories
JavaScript Answers

How to get the filename from the JavaScript FileReader?

Spread the love

Sometimes, we want to get the filename from the JavaScript FileReader.

In this article, we’ll look at how to get the filename from the JavaScript FileReader.

How to get the filename from the JavaScript FileReader?

To get the filename from the JavaScript FileReader, we can use the fileName property of the selected file.

For instance, we write:

<input type='file'>

to add a file input.

Then we write:

const reader = new FileReader();
reader.onload = (readerEvt) => {
  console.log(readerEvt.target);
};

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

to create the FileReader instance.

We select the input with document.querySelector.

Then we add a change event handler to the input with addEventListener.

In the event handler, we get the selected file with e.target.files.

Then we get the name of the selected file with file.name.

Conclusion

To get the filename from the JavaScript FileReader, we can use the fileName property of the selected file.

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 *