Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created July 2, 2023 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/3c7bc04bf3b4376b1b038fdf1dad58ea to your computer and use it in GitHub Desktop.
Save code-boxx/3c7bc04bf3b4376b1b038fdf1dad58ea to your computer and use it in GitHub Desktop.
Javascript Drag & Drop Upload

JAVASCRIPT DRAG & DROP UPLOAD

https://code-boxx.com/simple-drag-and-drop-file-upload/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/* (A) ENTIRE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
/* (B) WRAPPER */
.upwrap { max-width: 400px; }
/* (C) DRAG-DROP UPLOAD */
/* (C1) DROP ZONE */
.updrop {
color: #555;
font-weight: 700;
text-align: center;
padding: 50px 0;
border-radius: 10px;
border: 2px dashed #c9c9c9;
}
.updrop.highlight {
background: #ffff45;
border: 2px dashed #ed2e2e;
}
/* (D) UPLOAD STATS */
.upstat { margin-top: 10px; }
.uprow {
padding: 15px;
background: #e7e7e7;
}
.upstat .uprow:nth-child(even) { background: #f7f7f7; }
.upfile { margin-bottom: 5px; }
.upprog, .upbar, .uppercent {
width: 100%;
height: 20px;
}
.upprog {
position: relative;
background: #fff;
}
.upbar {
background: #d3e3ff;
width: 0;
transition: width 0.5s;
}
.uppercent {
position: absolute; top: 0; left: 0;
display: flex; align-items: center; justify-content: center;
}
.uppercent.bad {
text-overflow: ellipsis;
font-size: 14px;
color: #fff;
background: #b31717;
}
<!DOCTYPE html>
<html>
<head>
<title>Drag-and-drop Upload Demo</title>
<meta charset="utf-8">
<!-- (A) CSS + JS -->
<link rel="stylesheet" href="dd-upload.css">
<script src="dd-upload.js"></script>
</head>
<body>
<!-- (B) FILE DROP ZONE -->
<div id="demo"></div>
<!-- (C) ATTACH -->
<script>
ddup.init({
target : document.getElementById("demo"), // target html <div>
action : "dd-upload.php", // server-side upload handler
data : { key : "value" }, // optional, extra post data
size : 100000, // optional, max upload size 100kb
types : ["jpg", "jpeg", "webp", "png", "gif"] // optional, allowed file extensions
});
</script>
</body>
</html>
var ddup = {
// (A) ATTACH DRAG-DROP FILE UPLOADER
init : instance => {
// (A1) FLAGS + CSS CLASS
instance.target.classList.add("upwrap");
instance.upqueue = []; // upload queue
instance.uplock = false; // uploading in progress
instance.size = instance.size==undefined ? 0 : instance.size; // max upload size
instance.types = instance.types==undefined ? [] : instance.types; // allowed file types
for (let [k,v] of Object.entries(instance.types)) { instance.types[k] = v.toLowerCase(); }
// (A2) DRAG-DROP HTML INTERFACE
instance.target.innerHTML =
`<div class="updrop">Drop Files Here To Upload.</div>
<div class="upstat"></div>`;
instance.hzone = instance.target.querySelector(".updrop");
instance.hstat = instance.target.querySelector(".upstat");
// (A3) HIGHLIGHT DROP ZONE ON DRAG ENTER
instance.hzone.ondragenter = e => {
e.preventDefault();
e.stopPropagation();
instance.hzone.classList.add("highlight");
};
instance.hzone.ondragleave = e => {
e.preventDefault();
e.stopPropagation();
instance.hzone.classList.remove("highlight");
};
// (A4) DROP TO UPLOAD FILE
instance.hzone.ondragover = e => {
e.preventDefault();
e.stopPropagation();
};
instance.hzone.ondrop = e => {
e.preventDefault();
e.stopPropagation();
instance.hzone.classList.remove("highlight");
ddup.queue(instance, e.dataTransfer.files);
};
},
// (B) UPLOAD QUEUE
// * AJAX IS ASYNCHRONOUS, UPLOAD QUEUE PREVENTS SERVER FLOOD
queue : (instance, files) => {
// (B1) PUSH FILES INTO QUEUE + GENERATE HTML ROW
for (let f of files) {
// (B1-1) CREATE HTML FILE ROW
f.hstat = document.createElement("div");
f.hstat.className = "uprow";
f.hstat.innerHTML =
`<div class="upfile">${f.name} (${f.size} bytes)</div>
<div class="upprog">
<div class="upbar"></div>
<div class="uppercent">0%</div>
</div>`;
f.hbar = f.hstat.querySelector(".upbar");
f.hpercent = f.hstat.querySelector(".uppercent");
instance.hstat.appendChild(f.hstat);
// (B1-2) FILE SIZE CHECK
if (instance.size!=0 && f.size>instance.size) {
f.hpercent.classList.add("bad");
f.hpercent.innerHTML = `Over upload limit of ${instance.size} bytes`;
}
// (B1-3) FILE TYPE CHECK
else if (instance.types.length>0 && !instance.types.includes(f.name.split(".").pop().toLowerCase())) {
f.hpercent.classList.add("bad");
f.hpercent.innerHTML = `File type not allowed`;
}
// (B1-4) CHECKS OK - ADD TO UPLOAD QUEUE
else { instance.upqueue.push(f); }
}
// (B2) UPLOAD!
ddup.go(instance);
},
// (C) AJAX UPLOAD
go : instance => { if (!instance.uplock && instance.upqueue.length!=0) {
// (C1) UPLOAD STATUS UPDATE
instance.uplock = true;
// (C2) PLUCK OUT FIRST FILE IN QUEUE
let thisfile = instance.upqueue[0];
instance.upqueue.shift();
// (C3) UPLOAD DATA
let data = new FormData();
data.append("upfile", thisfile);
if (instance.data) { for (let [k, v] of Object.entries(instance.data)) {
data.append(k, v);
}}
// (C4) AJAX UPLOAD
let xhr = new XMLHttpRequest();
xhr.open("POST", instance.action);
// (C5) UPLOAD PROGRESS
let percent = 0, width = 0;
xhr.upload.onloadstart = e => {
thisfile.hbar.style.width = 0;
thisfile.hpercent.innerHTML = "0%";
};
xhr.upload.onloadend = e => {
thisfile.hbar.style.width = "100%";
thisfile.hpercent.innerHTML = "100%";
};
xhr.upload.onprogress = e => {
percent = Math.ceil((e.loaded / e.total) * 100) + "%";
thisfile.hbar.style.width = percent;
thisfile.hpercent.innerHTML = percent;
};
// (C6) UPLOAD COMPLETE
xhr.onload = function () {
// (C6-1) ERROR
if (this.response!= "OK" || this.status!=200) {
thisfile.hpercent.innerHTML = this.response;
}
// (C6-2) NEXT BETTER PLAYER!
else {
thisfile.hbar.style.width = "100%";
thisfile.hpercent.innerHTML = "100%";
instance.uplock = false;
ddup.go(instance);
}
};
// (C7) GO!
xhr.send(data);
}}
};
<?php
$source = $_FILES["upfile"]["tmp_name"];
$destination = $_FILES["upfile"]["name"];
move_uploaded_file($source, $destination);
echo "OK";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment