Skip to content

Instantly share code, notes, and snippets.

@kas-cor
Last active May 30, 2016 07:23
Show Gist options
  • Save kas-cor/be93b46c8ef6deba5fad3d4c6a917f5a to your computer and use it in GitHub Desktop.
Save kas-cor/be93b46c8ef6deba5fad3d4c6a917f5a to your computer and use it in GitHub Desktop.
HTML5 Drag & Drop files
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag & Drop files</title>
<style>
.dragdrop {
border: 2px;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="dragdrop"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
var dropTimer = {};
$(".dragdrop")[0].ondragover = function () {
clearTimeout(dropTimer);
$(".dragdrop").css("background", "#ccf");
return false;
};
$(".dragdrop")[0].ondragleave = function () {
dropTimer = setTimeout(function () {
$(".dragdrop").css("background", "#fff");
}, 500);
return false;
};
$(".dragdrop")[0].ondrop = function (event) {
event.preventDefault();
var maxFileSize = 1024 * 1024 * 5; // 5 Mb
var files = event.dataTransfer.files;
$(".dragdrop").css("background", "#fff");
for (var i in files) {
if (!files.hasOwnProperty(i)) {
continue;
}
if (files[i].size) {
if (files[i].size > maxFileSize) {
alert("Ошибка\n\nФайл " + files[i].name + " слишком большой: " + Math.round(files[i].size / 1024, 2) + " КБ<br /><br />Ограничение " + Math.round(maxFileSize / 1024) + " Кб");
return false;
}
} else {
alert("Ошибка\n\nПапки загружать запрещено!");
return false;
}
}
uploadFile(files);
};
function uploadFile(files) {
var formData = new FormData();
formData.append("field1", "value1");
formData.append("field2", "value2");
formData.append("field3", "value3");
for (var i in files) {
if (files.hasOwnProperty(i)) {
formData.append("files[]", files[i], files[i].name);
}
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://host.com/upload.php", true);
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
var percent = parseInt((e.loaded / e.total) * 100, 10) + "%";
console.log(percent);
}
};
xhr.onload = function (e) {
if (e.target.status === 200) {
if (e.target.responseText !== "ok") {
alert("Ошибка\n\n" + e.target.responseText);
}
} else {
alert("Ошибка\n\nЧто-то пошло не так");
}
};
xhr.send(formData);
}
<?php
function rearrange($arr) {
$new = array();
foreach ($arr as $key => $all) {
foreach ($all as $i => $val) {
$new[$i][$key] = $val;
}
}
return $new;
}
foreach (rearrange($_FILES['files']) as $file) {
if ($file['error'] == UPLOAD_ERR_OK) {
if (!move_uploaded_file($file['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . "/upload/" . $file['name'])) {
echo "err#2 - " . $file['name'] . "<br />\n";
}
} else {
echo "err#1[" . $file['error'] . "] - " . $file['name'] . "<br />\n";
}
}
echo "ok";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment