Explain Codes LogoExplain Codes Logo

How to get file name when user select a file via ``?

javascript
file-api
event-listeners
file-handling
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
TLDR

Fetching the file name from <input type="file"> is quite simple. Just attach a 'change' event listener and extract the name from the input's files[0]. Here's the short version:

document.querySelector('input[type="file"]').addEventListener('change', function() { console.log("Chosen file:", this.files[0].name); });

Implement this JavaScript snippet right after your file input HTML element:

<input type="file" />

This lightweight solution helps you dodge unnecessary server requests and boosts the user interface experience by providing quick feedback about the selected file.

Detailed explanation

Let's dive deeper into this topic. We will explore multiple ways to retrieve the file name and also discuss how to handle several files at once, extract additional file details, ensure cross-browser compatibility, and provide user feedback.

File details and multi-file handling

Fetching additional properties

Beyond just the file name, you can extract more file details — such as the file size and type — using the ‘File API’.

document.getElementById('fileInput').addEventListener('change', function() { if (this.files.length === 0) { console.log('No file selected. Relax, take a coffee ☕️.'); } else { const fileDetails = this.files[0]; console.log("Chosen file:", fileDetails.name); console.log("File Type: ", fileDetails.type); console.log("Size: ", fileDetails.size, "bytes"); } });

Adding a check for zero files ensures a graceful handle when no file is selected.

Handling multiple files

For <input> elements with the multiple attribute, we iterate over the files collection:

document.getElementById('multiFileInput').addEventListener('change', function() { // Loop through each selected file for(let i = 0; i < this.files.length; i++) { let file = this.files[i]; console.log(`File ${i + 1}:`, file.name); } });

User interaction and cross-compatibility

User-friendly notifications

Provide more comprehensible file size feedback by converting bytes into KB or MB:

function formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes'; // In case, the file is lighter than a feather. const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i]; }

Now, you can display file size with more compatibility within a user dialog or console log.

Ensuring compatibility

Not all browsers are created equal. Ensure your code is backward compatible. While modern browsers support these file handling features, some older browsers may falter.

Bonus

Unique ID handling

Ensure unique handling and prevent duplicates for each <input type="file"> on the page by using distinct id attributes.

Utilizing jQuery

$('.fileUploader').on('change', function() { alert("File picked: " + this.files[0].name); });

Use jQuery's .on('change') for cleaner, simpler event handling.

Validating user input

Before processing the file, validate the input to avoid unnecessary hiccups. This can be done efficiently with a touch of JavaScript.