drag-drop File
+ отображение
by rga4
HTML
<div id="drop-area">
<form class="my-form">
<p>Загрузите изображения с помощью диалога выбора файлов или перетащив нужные изображения в выделенную область</p>
<input type="file" id="fileElem" multiple accept="image/*" onchange="handleFiles(this.files)">
<label class="button" for="fileElem">Выбрать изображения</label>
<img id="preview_image" src="#" alt="image preview" width="200" />
</form>
</div>
CSS
#drop-area {
border: 2px dashed #ccc;
border-radius: 20px;
width: 480px;
font-family: sans-serif;
margin: 100px auto;
padding: 20px;
}
#drop-area.highlight {
border-color: purple;
}
p {
margin-top: 0;
}
.my-form {
margin-bottom: 10px;
}
#gallery {
margin-top: 10px;
}
#gallery img {
width: 150px;
margin-bottom: 10px;
margin-right: 10px;
vertical-align: middle;
}
.button {
display: inline-block;
padding: 10px;
background: #ccc;
cursor: pointer;
border-radius: 5px;
border: 1px solid #ccc;
}
.button:hover {
background: #ddd;
}
#fileElem {
display: none;
}
JavaScript
let dropArea = document.getElementById('drop-area');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
})
function preventDefaults (e) {
e.preventDefault()
e.stopPropagation()
}
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false)
});
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false)
})
function highlight(e) {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('highlight')
}
dropArea.addEventListener('drop', handleDrop, false);
function handleDrop(e) {
let dt = e.dataTransfer
let files = dt.files
handleFiles(files)
}
function handleFiles(files) {
([...files]).forEach(uploadFile)
}
function uploadFile(file) {
var reader = new FileReader();
reader.onloadend = function () {
document.getElementById("preview_image").src = reader.result;
}
reader.readAsDataURL(file);
}