Tuesday, December 17, 2024
HomeCSSDrag & Drop or Browse - File Upload Tutorial using HTML CSS...

Drag & Drop or Browse – File Upload Tutorial using HTML CSS and JavaScript

Hello Coders, In this tutorial, We are going to learn how to create drop and drop feature or browse to upload file feature using html, css and vanilla javascript.

What is drag & drop file upload ?

Most of the websites on internet, In order to upload file over the internet we used to use the browse feature previously. But nowadays drag and drop file upload feature has also become quite common. This feature was developed to make user experience more easier. Its so simple that, if you want to upload a file to a website all you have to do now is, just simply drag the file and its done. The file will get uploaded to the website or server.

What will be the final result of this project ?

  • User should be able to Upload image file with extensions jpeg, jpg, png.
  • If user uploads a file which is not supported, we will show an alert saying the file is not supported.
  • when the user uploads a file. The uploaded image should be displayed.

In this article we are going to learn how to build this feature using html css and vanilla javascript. Watch and read the video tutorial as well as this step by step article which will teach you how to build this project. You can download the complete source code of this project clicking on the download button at the bottom.

Drag and Drop or Browse – File upload tutorial in HTML CSS and JavaScript | Video Tutorial

In this video tutorial, I have shown how to build it in step by step. Watch the video tutorial and follow along with it if you are complete beginner and finding it hard to understand this article.

Drag and Drop or Browse – File Upload tutorial with HTML CSS and vanilla JavaScript | Source Codes

Follow the below step by step guide to build this project. I have also provided all the necessary source codes to make you understand it better. You can also download all the source codes completely by clicking on the download button at the bottom of this article.

Files required for this project :

  • index.html – For HTML
  • styles.css – For Styling
  • script.js – For adding drag and drop or browse feature

How do I create Drag and Drop or Browse File upload feature in HTML? Free HTML Source Code

Lets start with html. Inside your index.html file, Create the basic structure of the html document and add html, head, title, body tags. Follow below steps.

Step 1 : We will be using the font awesome cdn to import an icon from their library. You can see in the above demo that file icon is actually imported from the font awesome. I have provided the import code for it below.

Step 2 : Now link both our styles.css file as well script.js file to our html document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Drag, Drop & Browse</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
      integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>

Step 3 : We will create a div with class name ‘container’ and inside it we will create another div with class name ‘drag-area’. This drag area is going to be the area where we will drag our file to upload. Start typing the below code to complete the html part.

<div class="container">
  <h3>Upload your File :</h3>
  <div class="drag-area">
    <div class="icon">
      <i class="fas fa-images"></i>
    </div>

    <span class="header">Drag & Drop</span>
    <span class="header">or <span class="button">browse</span></span>
    <input type="file" hidden />
    <span class="support">Supports: JPEG, JPG, PNG</span>
  </div>
</div>

Output after HTML :

How do I design Drag and Drop or Browse File upload feature in CSS? Free CSS Source Code

Lets start with CSS. I have provided the source code of css below. Follow below step.

Step 4 : Inside the styles.css file. We will be using a custom google font i.e Poppins with weight 200, 300, 400, 500. Below I have provided the code for it. Start typing the css code from top to bottom and observe the changes it makes.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  min-height: 100vh;
  background: #e0eafc; /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #cfdef3, #e0eafc); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(
    to right,
    #cfdef3,
    #e0eafc
  ); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

.container {
  max-width: 650px;
  width: 100%;
  padding: 30px;
  background: #fff;
  border-radius: 20px;
  box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
}

.drag-area {
  height: 400px;
  border: 3px dashed #e0eafc;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  margin: 10px auto;
}

h3 {
  margin-bottom: 20px;
  font-weight: 500;
}

.drag-area .icon {
  font-size: 50px;
  color: #1683ff;
}

.drag-area .header {
  font-size: 20px;
  font-weight: 500;
  color: #34495e;
}

.drag-area .support {
  font-size: 12px;
  color: gray;
  margin: 10px 0 15px 0;
}

.drag-area .button {
  font-size: 20px;
  font-weight: 500;
  color: #1683ff;
  cursor: pointer;
}

.drag-area.active {
  border: 2px solid #1683ff;
}

.drag-area img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Output after CSS : 

How do I create Drag and Drop or Browse File upload feature in JavaScript? Free JavaScript Source Code

JavaScript is the main important thing in this project. Using javascript we can make it work as we want it to. Follow the below steps.

Step 5 : Now its time for JavaScript. First We will start by grabbing all the DOM elements that are required. We will also create a variable to store the file.

const dropArea = document.querySelector('.drag-area');
const dragText = document.querySelector('.header');

let button = dropArea.querySelector('.button');
let input = dropArea.querySelector('input');

let file;

Step 6 : Now we will implement the drag and drop feature first. Create a separate function to store and display the file. Inside the function we will define what are all the valid file types which we want to accept for the upload. 

We will define three event listeners, one for keep tracking of when the file is inside the drag area. One for tracking when it leaves the drag area and lastly one for when the user drops the file inside the drag area.

// when file is inside drag area
dropArea.addEventListener('dragover', (event) => {
  event.preventDefault();
  dropArea.classList.add('active');
  dragText.textContent = 'Release to Upload';
  // console.log('File is inside the drag area');
});

// when file leave the drag area
dropArea.addEventListener('dragleave', () => {
  dropArea.classList.remove('active');
  // console.log('File left the drag area');
  dragText.textContent = 'Drag & Drop';
});

// when file is dropped
dropArea.addEventListener('drop', (event) => {
  event.preventDefault();
  // console.log('File is dropped in drag area');

  file = event.dataTransfer.files[0]; // grab single file even of user selects multiple files
  // console.log(file);
  displayFile();
});

function displayFile() {
  let fileType = file.type;
  // console.log(fileType);

  let validExtensions = ['image/jpeg', 'image/jpg', 'image/png'];

  if (validExtensions.includes(fileType)) {
    // console.log('This is an image file');
    let fileReader = new FileReader();

    fileReader.onload = () => {
      let fileURL = fileReader.result;
      // console.log(fileURL);
      let imgTag = `<img src="${fileURL}" alt="">`;
      dropArea.innerHTML = imgTag;
    };
    fileReader.readAsDataURL(file);
  } else {
    alert('This is not an Image File');
    dropArea.classList.remove('active');
  }
}

Step 7 : Lets implement the browse feature. When the browse button is clicked we will simulate a click on the file input which opens up file explorer. We will listen for the change event and we will call the display function once user chooses a file.

button.onclick = () => {
  input.click();
};

// when browse
input.addEventListener('change', function () {
  file = this.files[0];
  dropArea.classList.add('active');
  displayFile();
});

Result of Drag & Drop or Browse – File Upload Feature : 

Download Source Code of Drag and Drop or Browse File Upload Feature with HTML, CSS and JavaScript. 

Download Code Files

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Posts

Categories