Create Drag and Drop File Uploader with HTML and Dropzone.js

Faraz

By Faraz -

Learn how to create a user-friendly drag-and-drop file uploader using HTML, CSS, and Dropzone.js.


create-drag-and-drop-file-uploader-with-html-and-dropzone-js.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

In this blog, we will learn how to create a drag-and-drop file uploader using HTML, CSS, and Dropzone.js. Dropzone.js is a popular JavaScript library that simplifies the process of adding file upload functionality to your web applications. With Dropzone.js, users can easily drag their files into a designated area or click to upload, making the process smooth and intuitive.

Prerequisites

Before you begin, make sure you have the following:

Now, let’s get started!

Source Code

Step 1 (HTML Code):

Create a new HTML file and add the following code to set up the structure of your uploader. Let's break down the HTML code step-by-step:

1. <!DOCTYPE html>:

  • This declares the document type and version of HTML (HTML5 in this case).

2. <html lang="en">:

  • The <html> tag is the root of the HTML document, and lang="en" specifies that the language of the document is English.

3. <head>:

  • Contains metadata and resources for the document.

a. <meta charset="UTF-8">:

  • Defines the character encoding for the document as UTF-8, ensuring that it can display a wide range of characters.

b. <meta name="viewport" content="width=device-width, initial-scale=1.0">:

  • Ensures that the page is responsive and sets the width of the page to match the screen width of the device, providing a better user experience on mobile.

c. <title>Drag and Drop File Uploader</title>:

  • Sets the title of the webpage as "Drag and Drop File Uploader," which is displayed in the browser tab.

d. External Stylesheets:

  • <link rel="stylesheet" href="https://fonts.goo..;700&amp;display=swap">: Loads the Poppins font from Google Fonts to style text.
  • <link rel="stylesheet" href="https://cdnjs.cloud..dropzone.min.css"/>: Loads Dropzone's CSS for styling the drag-and-drop area.
  • <link rel="stylesheet" href="styles.css">: Links an additional custom stylesheet (styles.css) for further customization.

4. <body>:

  • This is where the visible content and interactive elements of the page reside.

a. <h1>Modern Drag and Drop File Uploader</h1>:

  • A header that gives the title of the page, displayed as a heading.

b. Dropzone Form:

<form action="/file-upload" class="dropzone" id="fileDropzone">
    <div class="dz-message">
        Drag and drop files here or click to upload
    </div>
</form>
  • This form is the main component for file uploading.
  • class="dropzone": The dropzone class turns this form into a drag-and-drop file upload area using the Dropzone.js library.
  • action="/file-upload": Specifies the server endpoint (/file-upload) to which the uploaded files will be sent.
  • Inside the form, there’s a div with the class dz-message, which provides instructions to the user ("Drag and drop files here or click to upload").

c. File Info Table:

<table id="fileInfoTable">
    <thead>
        <tr>
            <th>File Name</th>
            <th>File Size (KB)</th>
            <th>File Type</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>
  • This table (id="fileInfoTable") will display the uploaded file details like file name, size, and type. Initially, the table body (<tbody>) is empty, but it will be populated dynamically with uploaded file information using JavaScript.

5. JavaScript Integration:

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js"></script>
<script src="script.js"></script>
  • First, the Dropzone.js library is imported from a CDN to provide the drag-and-drop file uploading functionality.
  • Next, script.js is linked, which is expected to contain custom JavaScript code that manages the file uploads and dynamically updates the file info table when a file is uploaded.

Step 2 (CSS Code):

Next, we need to style our uploader by adding our CSS. This will give our uploader an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

Let's break down the code section by section:

1. Global Styles for the body

body {
  font-family: 'Poppins', Arial, sans-serif;
  background-color: #f4f4f4;
  margin: 0;
  padding: 20px;
}
  • font-family: 'Poppins', Arial, sans-serif;: Sets the primary font to "Poppins," with fallbacks to Arial and any sans-serif font if Poppins is unavailable.
  • background-color: #f4f4f4;: Applies a light gray background color to the entire page.
  • margin: 0;: Removes the default margin from the body.
  • padding: 20px;: Adds 20 pixels of padding inside the body, giving space around the content.

2. Header Style for h1

h1 {
  text-align: center;
  color: #333;
}
  • text-align: center;: Centers the text in the header.
  • color: #333;: Sets the text color to a dark gray.

3. Styles for the Dropzone

.dropzone {
  border: 2px dashed #825CFF;
  border-radius: 10px;
  background-color: #ffffff;
  padding: 50px;
  text-align: center;
  font-size: 18px;
  color: #825CFF;
  transition: border-color 0.3s;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.dropzone:hover {
  border-color: #0056b3;
}
  • .dropzone: Styles the drag-and-drop area.
    • border: 2px dashed #825CFF;: Creates a dashed border in a purple color.
    • border-radius: 10px;: Rounds the corners of the dropzone.
    • background-color: #ffffff;: Sets the background color to white.
    • padding: 50px;: Adds 50 pixels of padding inside the dropzone for better spacing.
    • text-align: center;: Centers the text inside the dropzone.
    • font-size: 18px;: Sets the font size of the text.
    • color: #825CFF;: Sets the text color to the same purple used in the border.
    • transition: border-color 0.3s;: Smoothly transitions the border color over 0.3 seconds when it changes.
    • box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);: Adds a subtle shadow effect beneath the dropzone for depth.
  • .dropzone:hover: Changes the border color to a darker blue (#0056b3) when the user hovers over the dropzone, indicating interactivity.

4. Styles for the Table

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #825CFF;
  color: white;
}
  • table: Styles the table that displays uploaded file information.
    • width: 100%;: Makes the table take the full width of its container.
    • border-collapse: collapse;: Combines borders of adjacent cells to avoid double borders.
    • margin-top: 20px;: Adds space above the table.
    • box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);: Adds a shadow effect for depth.
    • background-color: #fff;: Sets the background color to white.
    • border-radius: 10px;: Rounds the corners of the table.
    • overflow: hidden;: Ensures no content spills outside the rounded corners.
  • th, td: Styles for table header cells and data cells.
    • padding: 15px;: Adds space inside each cell for better readability.
    • text-align: left;: Aligns text to the left.
    • border-bottom: 1px solid #ddd;: Adds a light gray border at the bottom of each cell for separation.
  • th: Specific styles for table header cells.
    • background-color: #825CFF;: Sets the header background to the same purple as the dropzone.
    • color: white;: Makes the header text white for contrast.

5. Styles for Buttons

button {
  background-color: #825CFF;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #4c18f7;
}
  • button: Styles for buttons in the page.
    • background-color: #825CFF;: Sets the button background color to purple.
    • color: white;: Makes the button text white.
    • border: none;: Removes any default border.
    • border-radius: 5px;: Rounds the corners of the button.
    • padding: 8px 12px;: Adds padding inside the button for better clickability.
    • cursor: pointer;: Changes the cursor to a pointer when hovering over the button, indicating it's clickable.
    • transition: background-color 0.3s;: Smoothly transitions the background color when hovered.
  • button:hover: Changes the background color to a darker purple (#4c18f7) when the button is hovered, indicating interactivity.

6. Hiding Dropzone Error Messages

.dz-error-message {
  display: none !important;
}

.dz-error-mark {
  display: none !important;
}
  • .dz-error-message and .dz-error-mark: These classes are used to hide error messages and error indicators from the Dropzone plugin. The !important rule ensures that these styles take precedence over any other conflicting styles.

7. Media Queries for Responsive Design

@media (max-width: 600px) {
  .dropzone {
      padding: 30px;
      font-size: 16px;
  }

  th, td {
      padding: 10px;
  }
}
  • @media (max-width: 600px): This media query applies styles when the viewport width is 600 pixels or less, making the design responsive for smaller screens.
    • .dropzone: Reduces padding to 30 pixels and font size to 16 pixels for better fit on smaller screens.
    • th, td: Reduces padding in table cells to 10 pixels for better spacing on smaller screens.
body {
  font-family: 'Poppins', Arial, sans-serif;
  background-color: #f4f4f4;
  margin: 0;
  padding: 20px;
}

h1 {
  text-align: center;
  color: #333;
}

.dropzone {
  border: 2px dashed #825CFF;
  border-radius: 10px;
  background-color: #ffffff;
  padding: 50px;
  text-align: center;
  font-size: 18px;
  color: #825CFF;
  transition: border-color 0.3s;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.dropzone:hover {
  border-color: #0056b3;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

th, td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #825CFF;
  color: white;
}

button {
  background-color: #825CFF;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #4c18f7;
}

.dz-error-message{
display:none !important;
}

.dz-error-mark{
display:none !important;
}

@media (max-width: 600px) {
  .dropzone {
      padding: 30px;
      font-size: 16px;
  }

  th, td {
      padding: 10px;
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Let’s break down the JavaScript code step by step:

1. Dropzone Configuration

Dropzone.options.fileDropzone = {
  autoProcessQueue: true, // Automatically upload files
  maxFilesize: 5, // Max file size in MB
  acceptedFiles: '.jpeg,.jpg,.png,.pdf', // Accepted file types
  init: function () {
    this.on('addedfile', function (file) {
      // Display file info when a file is added
      displayFileInfo(file, this);
    });
  },
};
  • Dropzone.options.fileDropzone: This line configures the Dropzone instance for a specific element with the ID fileDropzone.
  • autoProcessQueue: true: Files are automatically uploaded after they are added to the Dropzone, without needing a manual trigger.
  • maxFilesize: 5: Sets the maximum file size limit to 5 megabytes. If a user tries to upload a file larger than this, an error will be displayed.
  • acceptedFiles: '.jpeg,.jpg,.png,.pdf': Specifies the accepted file types for upload. In this case, only JPEG, JPG, PNG images, and PDF documents are allowed.
  • init: function () { ... }: This function is called when the Dropzone is initialized. It sets up an event listener for the addedfile event.
    • this.on('addedfile', function (file) { ... }): When a file is added to the Dropzone, this function executes, calling the displayFileInfo function to show the file information in a table.

2. Displaying File Information

function displayFileInfo(file, dropzoneInstance) {
  var tableBody = document.querySelector('#fileInfoTable tbody');

  var row = document.createElement('tr');

  var fileNameCell = document.createElement('td');
  fileNameCell.textContent = file.name;

  var fileSizeCell = document.createElement('td');
  fileSizeCell.textContent = (file.size / 1024).toFixed(2); // Convert size to KB

  var fileTypeCell = document.createElement('td');
  fileTypeCell.textContent = file.type;

  var cancelButton = document.createElement('button');
  cancelButton.textContent = 'Cancel';

  cancelButton.addEventListener('click', function () {
    // Remove file from Dropzone and table
    dropzoneInstance.removeFile(file);
    row.remove();
  });

  var actionCell = document.createElement('td');
  actionCell.appendChild(cancelButton);

  row.appendChild(fileNameCell);
  row.appendChild(fileSizeCell);
  row.appendChild(fileTypeCell);
  row.appendChild(actionCell);

  tableBody.appendChild(row);
}
  • function displayFileInfo(file, dropzoneInstance): This function displays the details of the uploaded file in a table.
  • var tableBody = document.querySelector('#fileInfoTable tbody');: Selects the table body where file information will be displayed, targeting the table with the ID fileInfoTable.
  • var row = document.createElement('tr');: Creates a new table row to hold the file information.
  • Creating Cells:
    • File Name:
      var fileNameCell = document.createElement('td');
      fileNameCell.textContent = file.name;
      • Creates a cell for the file name and assigns the name of the file to its text content.
    • File Size:
      var fileSizeCell = document.createElement('td');
      fileSizeCell.textContent = (file.size / 1024).toFixed(2);
      • Creates a cell for the file size. It converts the size from bytes to kilobytes (by dividing by 1024) and formats it to two decimal places.
    • File Type:
      var fileTypeCell = document.createElement('td');
      fileTypeCell.textContent = file.type;
      • Creates a cell for the file type and sets its text content to the file's MIME type.
  • Cancel Button:
    var cancelButton = document.createElement('button');
    cancelButton.textContent = 'Cancel';
    • Creates a cancel button to allow the user to remove the file from the upload queue.
    • Cancel Button Click Event:
      cancelButton.addEventListener('click', function () {
        dropzoneInstance.removeFile(file);
        row.remove();
      });
      • Adds a click event listener to the button. When clicked, it removes the file from the Dropzone using dropzoneInstance.removeFile(file) and also removes the corresponding row from the table using row.remove().
  • Appending Cells to the Row:
    row.appendChild(fileNameCell);
    row.appendChild(fileSizeCell);
    row.appendChild(fileTypeCell);
    row.appendChild(actionCell);
    • Each cell created earlier is appended to the row, forming a complete representation of the file.
  • Appending the Row to the Table Body:
    tableBody.appendChild(row);
    • Finally, the row containing the file information is appended to the table body, making it visible in the table.
Dropzone.options.fileDropzone = {
  autoProcessQueue: true, // Automatically upload files
  maxFilesize: 5, // Max file size in MB
  acceptedFiles: '.jpeg,.jpg,.png,.pdf', // Accepted file types
  init: function () {
    this.on('addedfile', function (file) {
      // Display file info when a file is added
      displayFileInfo(file, this);
    });
  },
};

// Function to display file information in the table
function displayFileInfo(file, dropzoneInstance) {
  var tableBody = document.querySelector('#fileInfoTable tbody');

  // Create a new row for the table
  var row = document.createElement('tr');

  // Create table cells for file name, size, type, and action (cancel)
  var fileNameCell = document.createElement('td');
  fileNameCell.textContent = file.name;

  var fileSizeCell = document.createElement('td');
  fileSizeCell.textContent = (file.size / 1024).toFixed(2); // Convert size to KB

  var fileTypeCell = document.createElement('td');
  fileTypeCell.textContent = file.type;

  // Create a cancel button
  var cancelButton = document.createElement('button');
  cancelButton.textContent = 'Cancel';

  // Handle cancel button click
  cancelButton.addEventListener('click', function () {
    // Remove file from Dropzone and table
    dropzoneInstance.removeFile(file);
    row.remove();
  });

  var actionCell = document.createElement('td');
  actionCell.appendChild(cancelButton);

  // Append cells to the row
  row.appendChild(fileNameCell);
  row.appendChild(fileSizeCell);
  row.appendChild(fileTypeCell);
  row.appendChild(actionCell);

  // Append the row to the table body
  tableBody.appendChild(row);
}

Final Output:

create-drag-and-drop-file-uploader-with-html-and-dropzone-js.gif

Conclusion:

Creating a drag-and-drop file uploader using HTML, CSS, and Dropzone.js is an excellent way to improve the way users upload files on your website. In this guide, we walked through the steps needed to set up a simple and modern uploader.

You learned how to create a clean and user-friendly interface that allows users to easily drag files into a designated area or click to upload. Additionally, Dropzone.js provides various features, such as file previews and error handling, which can further enhance your uploader.

As web development continues to evolve, incorporating easy-to-use tools like Dropzone.js will make your web applications more appealing and functional. You can take this basic uploader and customize it further to fit your unique needs.

Feel free to experiment with the styles and functionalities discussed in this blog post. With some creativity, you can make the uploader match your website’s design and provide a seamless experience for your users.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺