How to get a file’s name when the user selects a file via a file input with JavaScript?

You can get the name of the file selected by the user using JavaScript when they select a file via a file input.

To do this we write:

HTML:

<input type="file" id="fileInput" onchange="getFileDetails()">

JavaScript:

<script>
    function getFileDetails() {
        const fileInput = document.getElementById('fileInput');
        
        // Check if any file is selected
        if (fileInput.files.length > 0) {
            // Get the name of the selected file
            const fileName = fileInput.files[0].name;
            
            // Display the file name
            console.log("Selected file name: " + fileName);
        }
    }
</script>

In this example, we have an <input> element of type "file" with the id "fileInput".

We’ve added an onchange event handler to the file input that calls the getFileDetails() function when the user selects a file.

In the getFileDetails() function, we get the file input element using document.getElementById('fileInput').

Then we check if any file is selected by checking the length of the files property.

If a file is selected, we get the name of the selected file using fileInput.files[0].name.

We display the file name in the console, but you can use it as needed for your application.

When the user selects a file using the file input, the file name will be printed to the console.

You can then use this file name as needed in your JavaScript code.