In JavaScript è semplice mostrare il nome di un file scelto per l'upload.
Dato il seguente form:
<form action="" method="post" enctype="multipart/form-data">
<div>
<span class="file">
<input type="file" name="file">
</span>
<span class="file-name"></span>
<input type="submit" value="Upload">
</div>
</form>
Possiamo scrivere il seguente codice JavaScript:
'use strict';
(function() {
const handleFileInputs = selector => {
const form = document.querySelector(selector);
const showName = el => {
if(!Array.isArray(el.files) || el.files.length === 0) {
return;
}
const name = el.files[0].name;
el.parentNode.nextElementSibling.innerHTML = name;
};
if(form !== null) {
const inputs = form.querySelectorAll('input[type="file"]');
inputs.forEach(input => {
input.addEventListener('change', () => {
showName(this);
}, false);
}
}
};
document.addEventListener('DOMContentLoaded', () => {
handleFileInputs('#upload');
}, false);
})();