HomeJavascriptDrag & Drop File Upload | Vanilla Javascript

Drag & Drop File Upload | Vanilla Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to create a drag-and-drop file upload. To make this project we need HTML, CSS and Javascript.
 
We do not make use of any external libraries to implement this functionality. This is an intermediate-level javascript project. I would not suggest this for absolute javascript beginners.
 
If you are looking for more such projects to improve your javascript skills check out this playlist here. This playlist consists of about 100+ javascript projects. The difficulty of the level of these projects varies from easy to quite complex ones. Hence this playlist is suitable for all kinds of javascript learners including beginners and experts.

Video Tutorial:

If you are interested to learn by watching a video tutorial you can check out the video down below. Also subscribe to my youtube channel where I post new tips, tricks and tutorials every alternate day.

Project Folder Structure:

Before we start coding, let us look at the project folder structure. We create a project folder called – ‘Drag and Drop File Upload’. Within this folder, we have three files. These files are – index.html, style.css and script.js. The first file is the HTML document. Next, we have the stylesheet and finally, we have the script file.

HTML:

We begin with the HTML code. First, copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Drag & Drop File Upload</title>
    <!-- Font Awesome Icons -->
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
    />
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <input type="file" id="upload-button" multiple accept="image/*" />
      <label for="upload-button"
        ><i class="fa-solid fa-upload"></i>&nbsp; Choose Or Drop Photos
      </label>
      <div id="error"></div>
      <div id="image-display"></div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style the file input button and add a layout to the uploaded images using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #f5f8ff;
}
.container {
  background-color: #ffffff;
  width: 60%;
  min-width: 37.5em;
  padding: 3.12em 1.87em;
  position: absolute;
  transform: translateX(-50%);
  left: 50%;
  top: 1em;
  box-shadow: 0 1.25em 3.43em rgba(0, 0, 0, 0.08);
  border-radius: 0.5em;
}
input[type="file"] {
  display: none;
}
label {
  display: block;
  position: relative;
  background-color: #025bee;
  color: #ffffff;
  font-size: 1.1em;
  text-align: center;
  width: 16em;
  padding: 1em 0;
  border-radius: 0.3em;
  margin: 0 auto 1em auto;
  cursor: pointer;
}
#image-display {
  position: relative;
  width: 90%;
  margin: 0 auto;
  display: flex;
  justify-content: space-evenly;
  gap: 1.25em;
  flex-wrap: wrap;
}
#image-display figure {
  width: 45%;
}
#image-display img {
  width: 100%;
}
#image-display figcaption {
  font-size: 0.8em;
  text-align: center;
  color: #5a5861;
}
.active {
  border: 0.2em dashed #025bee;
}
#error {
  text-align: center;
  color: #ff3030;
}

Javascript:

We finally implemented the functionality of our project. Once more copy the code below and paste it into your script file.

let uploadButton = document.getElementById("upload-button");
let chosenImage = document.getElementById("chosen-image");
let fileName = document.getElementById("file-name");
let container = document.querySelector(".container");
let error = document.getElementById("error");
let imageDisplay = document.getElementById("image-display");

const fileHandler = (file, name, type) => {
  if (type.split("/")[0] !== "image") {
    //File Type Error
    error.innerText = "Please upload an image file";
    return false;
  }
  error.innerText = "";
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onloadend = () => {
    //image and file name
    let imageContainer = document.createElement("figure");
    let img = document.createElement("img");
    img.src = reader.result;
    imageContainer.appendChild(img);
    imageContainer.innerHTML += `<figcaption>${name}</figcaption>`;
    imageDisplay.appendChild(imageContainer);
  };
};

//Upload Button
uploadButton.addEventListener("change", () => {
  imageDisplay.innerHTML = "";
  Array.from(uploadButton.files).forEach((file) => {
    fileHandler(file, file.name, file.type);
  });
});

container.addEventListener(
  "dragenter",
  (e) => {
    e.preventDefault();
    e.stopPropagation();
    container.classList.add("active");
  },
  false
);

container.addEventListener(
  "dragleave",
  (e) => {
    e.preventDefault();
    e.stopPropagation();
    container.classList.remove("active");
  },
  false
);

container.addEventListener(
  "dragover",
  (e) => {
    e.preventDefault();
    e.stopPropagation();
    container.classList.add("active");
  },
  false
);

container.addEventListener(
  "drop",
  (e) => {
    e.preventDefault();
    e.stopPropagation();
    container.classList.remove("active");
    let draggedData = e.dataTransfer;
    let files = draggedData.files;
    imageDisplay.innerHTML = "";
    Array.from(files).forEach((file) => {
      fileHandler(file, file.name, file.type);
    });
  },
  false
);

window.onload = () => {
  error.innerText = "";
};

That’s it for this tutorial. Your drag-and-drop file upload project is now ready. If you face any issues while creating this project you can download the source code by clicking the – ‘Download Code’ below. Also if you have any queries, suggestions or feedback comment below.

Previous articleMCQ – 15/10/22
Next articleMCQ – 17/10/22
RELATED ARTICLES

1 COMMENT

  1. work really well on client side but can not post the file input in drag dop mode.
    Dropped file does not attached to the file input. so it is not get posted.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

sixteen − 3 =

Most Popular