How to Get the Filename From the Javascript Filereader

As a web developer, you may come across a scenario where you need to extract the filename of a selected file using JavaScript.

This could be required when you want to display the name of the file selected by the user on the front-end or perform some validation on the file type or size.

In this article, we’ll take a look at how to extract the filename from a FileReader in JavaScript.


Introduction to FileReader API

The FileReader API is a built-in JavaScript API that allows you to read the contents of a file or a Blob object as an ArrayBuffer, a string, or a data URL.

This API is useful when you want to read the contents of a file selected by the user in an HTML form.

Here’s an example of how to read the contents of a file using the FileReader API:

const input = document.querySelector("input[type='file']");
const reader = new FileReader();

reader.onload = function() {
console.log(reader.result);
};

input.addEventListener("change", function() {
reader.readAsText(input.files[0]);
});

In the above code, we first select the file input element and create a new instance of the FileReader API.

We then attach an event listener to the change event of the input element, which triggers the readAsText method of the FileReader instance and logs the result to the console.

Extracting the Filename from FileReader

To extract the filename from a FileReader instance, we need to access the file property of the input element.

The file property contains an object of the type File, which has a property named name that represents the filename.

Here’s an example of how to extract the filename:

const input = document.querySelector("input[type='file']");
const reader = new FileReader();

reader.onload = function() {
console.log(input.files[0].name);
};

input.addEventListener("change", function() {
reader.readAsText(input.files[0]);
});

In the above code, we log the name property of the File object to the console instead of the result property of the FileReader instance.


Conclusion

In this blog post, we learned how to extract the filename from a FileReader instance in JavaScript.

We saw how to read the contents of a file using the FileReader API and how to access the file property of the input element to extract the filename.

This technique can be useful when you want to display the name of the selected file on the front-end or perform some validation on the file type or size.