<form id="form_upload" action="/path-to-handler" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000"/>
<input name="userfiles[]" type="file" multiple/>
<div id="previews"></div>
<input type="submit" value="Отправить"/>
</form>
<style>
img {
max-width: 150px;
margin-right: 5px;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('#form_upload');
const inputFile = form ? form.querySelector('[name="userfiles[]"]') : undefined;
if (!form || !inputFile) {
return void console.error('Form of input[type=file] not found');
}
const imagesPreviews = [];
const previewsContainer = document.querySelector('#previews');
inputFile.addEventListener('change', function () {
if (!previewsContainer || !this.files) {
return;
}
previewsContainer.innerHTML = '';
let objectUrl;
while (objectUrl = imagesPreviews.shift()) {
URL.revokeObjectURL(objectUrl);
}
[].forEach.call(this.files, function (file) {
const objectUrl = URL.createObjectURL(file);
const image = document.createElement('img');
image.alt = file.name;
image.src = objectUrl;
previewsContainer.appendChild(image);
imagesPreviews.push(objectUrl);
});
});
form.addEventListener('submit', function (e) {
e.preventDefault();
fetch(this.action, {
method: this.method,
body: new FormData(this)
}).then(function (res) {
return res.json();
}).then(function (response) {
// handle response
});
});
});
</script>