How to get file name when user select a file via ``?
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:
Implement this JavaScript snippet right after your file input HTML element:
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’.
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:
User interaction and cross-compatibility
User-friendly notifications
Provide more comprehensible file size feedback by converting bytes into KB or MB:
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
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.
Was this article helpful?