Bootstrap 4 file input doesn't show the file name
To display the selected file name in Bootstrap 4, use the custom-file
class structure. Assign custom-file-input
to your input element and pair it with a custom-file-label
. Here is a code snippet that displays the file name when a file is selected:
The Javascript code listens to a change event on the file input, hence updating the label text with the file name every time a file is selected.
Handling the Multi-file situation 📁
For scenarios that allow multiple file upload, concatenate the file names. JavaScript's .map
and .join
functions can be used to achieve this. Note that the multiple
attribute has to be added to the file input field:
And the JavaScript adapted to handle an array of files:
Event Delegation to the Rescue! 🦸♂️
In cases where file inputs are added to the DOM dynamically, use event delegation by attaching the event listener to a parent element present during page load:
This ensures that all matching inputs, even those added later, will correctly display file names when a file is selected.
The Inherent Beauty of Simple Code
To make your code optimal, avoid adding unnecessary complexity. Ensure that your code is compatible with Bootstrap 4. Here's a refactored example:
Goodbye Chrome's fake path! 🚫
Chrome appends a fake path to the file's name for security reasons. However, this can be removed by using:
Additional Considerations
When creating a file input, here are some extra considerations:
- Error Handling: Prepare for errors or invalid file types. User guidance is key.
- Accessibility: Make the input user-friendly for all. Label your inputs properly and make sure keyboard navigation is possible.
- Styling: Maintain a consistent style. Your site's thematic consistency depends on it.
- Security: Always validate and sanitize files on the server side. Forget not, client-side validation isn't enough.
Was this article helpful?