Multiple File Selection
You'll learn how to let users select multiple files at once and display a removable file list before upload.
What Is Multiple File Selection?
When you add the multiple attribute to a file input, users can select more than one file in a single action. This is essential for photo galleries, document uploads, or any scenario where bulk file selection improves user experience. However, with multiple files comes the need to show users what they've selected and give them control to remove individual files before submitting.
Displaying Multiple Files
After a user selects files, you can loop through the FileList object and display each file's name and size:
const fileInput = document.querySelector('input[type="file"]');
const fileListContainer = document.querySelector('#file-list');
fileInput.addEventListener('change', (e) => {
const files = Array.from(e.target.files);
fileListContainer.innerHTML = files.map((file, index) => `
<div class="file-item" data-index="${index}">
<span>${file.name} (${(file.size / 1024).toFixed(2)} KB)</span>
<button type="button" class="remove-btn">Remove</button>
</div>
`).join('');
});
Removing Selected Files
The tricky part: you can't directly modify a FileList, so you must maintain a separate array and use a DataTransfer object to update the input:
let selectedFiles = [];
fileInput.addEventListener('change', (e) => {
selectedFiles = Array.from(e.target.files);
updateFileDisplay();
});
fileListContainer.addEventListener('click', (e) => {
if (e.target.classList.contains('remove-btn')) {
const index = e.target.closest('.file-item').dataset.index;
selectedFiles.splice(index, 1);
updateFileInput();
updateFileDisplay();
}
});
function updateFileInput() {
const dt = new DataTransfer();
selectedFiles.forEach(file => dt.items.add(file));
fileInput.files = dt.files;
}
Key Takeaway: Multiple file selection requires the multiple attribute, displaying a list for user review, and using a DataTransfer object to programmatically update the file input when users remove selections.