Bootstrap 4中custom-file-input类如何显示上传文件名?
custom-file-input Great question! The custom-file-input class works differently than form-control because it’s part of Bootstrap’s custom file input component—this component visually hides the native file input and uses a dedicated label element to show the selected filename. Here’s how to fix this:
Step 1: Use the Full Bootstrap Custom File Structure
First, make sure your HTML follows the complete component structure. You can’t just apply custom-file-input alone; it needs a parent container and a paired label:
<div class="custom-file"> <input type="file" class="custom-file-input" id="yourFileInput"> <!-- This label will display the filename --> <label class="custom-file-label" for="yourFileInput">Select a file...</label> </div>
- The
custom-filecontainer wraps both elements to handle the styling. - The
custom-file-labelmust have aforattribute matching the input’sidto link them.
Step 2: Add JavaScript to Update the Label
The native file input won’t automatically update the custom label, so you’ll need a small script to sync the selected filename. Here are two options:
Option 1: Vanilla JavaScript
This works without any libraries:
// Target your custom file input const fileInput = document.querySelector('.custom-file-input'); fileInput.addEventListener('change', function(e) { // Get the selected file name (fallback to default text if no file is chosen) const selectedFileName = e.target.files[0]?.name || 'Select a file...'; // Update the label text this.nextElementSibling.textContent = selectedFileName; });
Option 2: jQuery (if you’re using Bootstrap 4 or older)
If you already have jQuery in your project, this is a concise way to handle it:
$('.custom-file-input').on('change', function() { // Extract the filename from the full path (browsers hide the full path for security) let fileName = $(this).val().split('\\').pop(); // Update the label $(this).next('.custom-file-label').text(fileName || 'Select a file...'); });
Bonus: Handle Multiple Files
If you’ve added the multiple attribute to your input, modify the script to show how many files were selected:
fileInput.addEventListener('change', function(e) { const fileCount = e.target.files.length; let displayText; if (fileCount === 0) { displayText = 'Select files...'; } else if (fileCount === 1) { displayText = e.target.files[0].name; } else { displayText = `${fileCount} files selected`; } this.nextElementSibling.textContent = displayText; });
Note for Bootstrap 5+
If you’re using Bootstrap 5 or later, the framework’s built-in JavaScript (included in bootstrap.bundle.min.js) already handles this filename update—just make sure you’ve loaded the full Bootstrap bundle, and you won’t need to write custom JS!
内容的提问来源于stack exchange,提问作者Mike

