Home/Blog/How to make a Drag-and-Drop file uploader

How to make a Drag-and-Drop file uploader

This isย aย comprehensive guide toย creating aย web-based Drag-and-Drop file uploader using the common tech stack: JavaScript, HTML, and CSS. Weย will cover aย DIY approach and then follow upย with aย SaaS solutionย โ€” Uploadcare File Uploader.

Drag-and-Drop functionality makes the uploading process easier and more intuitive for the end user onย desktops. Instead ofย searching for aย file onย the device, itย isย possible toย drag itย into the webpage area. The uploading process can beย delayed, and the file previewing functionality could beย beneficial inย this case, allowing the user toย see what will beย uploaded. This isย especially helpful for images.

DIY vsย Libraries vsย SaaS: pros and cons

There are several ways how toย implement drag-and-drop functionality for files:

  • From scratch with JavaScript: this approach provides full control over the process but requires more effort from aย developer
  • Using JSย libraries: these provide ready solutions making developments easier. However, sometimes they may require additional codebase preparation.
  • SaaS: services like Uploadcare offer ready-to-use solutions for uploading files, including Drag-and-Drop, storing these files, and processing the information.

So, letโ€™s see the hard way and the easiest inย practice!

If you prefer learning from videos, our YouTube tutorial offers a visual guide on implementing a drap-and-drop uploader with preview features.

Stepย 1: Creating aย file uploader

Creating aย simple HTML uploader and Drag-and-Drop boilerplate

Letโ€™s start with creating aย simple HTMLย element:

<input type="file">

After that, letโ€™s create aย drag-and-drop container thatโ€™ll serve asย aย visual representation ofย the file-dropping area. Some styling will beย required soย the CSS file isย needed asย well.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drag-and-Drop File Uploader</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Drag-and-Drop File Uploader</h1>
  <div id="drop-area">
    Drag here to preview
  </div>
  <input type="file" id="file-input" multiple hidden>
  <div id="preview-container"></div>
  <script src="script.js"></script>
</body>
/* style.css */
body {
  margin: 0;
  padding: 20px;
  font-family: sans-serif;
}

h1 {
  text-align: center;
}

#drop-area {
  width: 400px;
  height: 200px;
  margin: 20px auto;
  text-align: center;
  line-height: 200px;
  border: 2px dashed #ccc;
  cursor: pointer;
}

#preview-container {
  text-align: center;
}

The interface looks asย follows:

Basic drag-and-drop file uploader interfaceBasic drag-and-drop file uploader interface

Using Drag-and-Drop JavaScript events

Following JSย events are involved inย Drag-and-Drop functionality:

  • dragenter: fires when anย element isย dragged into another element.
  • dragover: fires when anย element isย being continuously dragged over another element
  • dragleave: fires when anย element isย dragged outside another element
  • drop: fires when anย element isย being dropped onto (into) another element.

Now letโ€™s add some code toย the script.js file toย process the events. Weโ€™ll beย using anย element with the drop-area IDย as our drag-and-drop container. Inย our case, weโ€™ll use the drop event toย detect when aย file isย released into the drag container area byย releasing the mouse button. Additionally, weโ€™ll prevent the default browser behaviour when dragging aย file over the container.

const dropArea = document.getElementById('drop-area');
const fileInput = document.getElementById('file-input');

// Utility function to prevent default browser behavior
function preventDefaults(e) {
  e.preventDefault();
  e.stopPropagation();
}

// Preventing default browser behavior when dragging a file over the container
dropArea.addEventListener('dragover', preventDefaults);
dropArea.addEventListener('dragenter', preventDefaults);
dropArea.addEventListener('dragleave', preventDefaults);

// Handling dropping files into the area
dropArea.addEventListener('drop', handleDrop);

// Weโ€™ll discuss `handleDrop` function down the road
function handleDrop(e) { /* ... */ }

Enhancing user experience withย UI indication

Toย improve user experience, letโ€™s change the visual properties ofย the drag-and-drop area based onย the current dragging state. Assigning aย class toย the element would beย anย optimal solution here.

dropArea.addEventListener('dragover', () => {
  dropArea.classList.add('drag-over');
});

dropArea.addEventListener('dragleave', () => {
  dropArea.classList.remove('drag-over');
});

Toย reflect these changes, weย also need toย update the CSS:

#drop-area.drag-over {
  background-color: #eee;
}
Indicating current dragging state byย changing container backgroundIndicating current dragging state byย changing container background

Stepย 2: Implementing previews

Previewing makes itย easier for the user toย navigate through the files before they are uploaded toย the server.

Implementing previews with FileReader API

FileReader API allows accessing file contents and metadata. Weย will beย using this functionality toย create logic for our previews.

The dragover and dragenter events were managed previously, now letโ€™s manage the actual โ€œdropโ€ part ofย our drag-and-drop uploader.

Hereโ€™s the code for the handleDrop function:

function handleDrop(e) {
  e.preventDefault();

  // Getting the list of dragged files
  const files = e.dataTransfer.files;

  // Checking if there are any files
  if (files.length) {
    // Assigning the files to the hidden input from the first step
    fileInput.files = files;

    // Processing the files for previews (next step)
    handleFiles(files);
  }
}

// Weโ€™ll discuss `handleFiles` function down the road
function handleFiles(files) { /* ... */ }

Now since weย have the files list, letโ€™s improve the function that processes themย โ€” handleFiles:

function handleFiles(files) {
  for (const file of files) {
    // Initializing the FileReader API and reading the file
    const reader = new FileReader();
    reader.readAsDataURL(file);

    // Once the file has been loaded, fire the processing
    reader.onloadend = function (e) {
      const preview = document.createElement('img');

      if (isValidFileType(file)) {
        preview.src = e.target.result;
      }

      // Apply styling
      preview.classList.add('preview-image');
      const previewContainer = document.getElementById('preview-container');
      previewContainer.appendChild(preview);
    };
  }
}

// Weโ€™ll discuss `isValidFileType` function down the road
function isValidFileType() {
  return true;
}

The piece above uses the isValidFileType function. Its purpose isย toย validate the input file based onย its MIME data. Hereโ€™s the code for this function:

function isValidFileType(file) {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  return allowedTypes.includes(file.type);
}

The code supports common image types and can beย extended according toย your needs.

File previews should also have minimal styling. Hereโ€™s the CSS code for the preview-image class:

.preview-image {
  object-fit: cover;
  width: 100px;
  height: 100px;
  margin: 10px;
  border: 1px solid #ddd;
}

Our simple file uploader has just learned aย new skill: file previewing. Here itย is:

Drag-and-Drop file uploader with previewing functionalityDrag-and-Drop file uploader with previewing functionality

Creating preview placeholders for unsupported file types

Our file uploader supports all file types, but not all ofย them can beย previewed. Inย case ifย aย user uploads, letโ€™s say, aย ZIP archive, weย need toย use aย placeholder image instead ofย previewing raw file contents. First, letโ€™s provide the path toย the placeholder image atย the top ofย our script:

const placeholderIcon = 'file-placeholder.jpg';

Name the desired placeholder icon file-placeholder.jpg and put itย into the root folder ofย the project.

Now weย can add else branch toย the handleFiles function:

function handleFiles(files) {
  for (const file of files) {
    // Initializing the FileReader API and reading the file
    const reader = new FileReader();
    reader.readAsDataURL(file);

    // Once the file has been loaded, fire the processing
    reader.onloadend = function (e) {
      const preview = document.createElement('img');

      if (isValidFileType(file)) {
        preview.src = e.target.result;
      } else {
        preview.src = placeholderIcon;
      }

      // Apply styling
      preview.classList.add('preview-image');
      const previewContainer = document.getElementById('preview-container');
      previewContainer.appendChild(preview);
    };
  }
}

Now, ifย the file isย invalid for previewing, the path toย the placeholder icon will beย added asย the preview source. The screenshot below demonstrates that even ifย the file isย not previewed, itย isย still contained inย the files list ofย the hidden file uploader input field.

Drag-and-Drop file uploader with unsupported file type preview functionalityDrag-and-Drop file uploader with unsupported file type preview functionality

Stepย 3: Organizing server uploads

Inย this article, weย focus primarily onย the front-end part ofย the DIY uploader. The files collected inย the hidden field could beย sent toย the server and processed differently based onย your needs. Please referย to one ofย myย previous articles toย see aย detailed example ofย possible implementation with JavaScript AJAX and PHP.

Simplifying the process with Uploadcare

How Uploadcare can simplify each ofย the steps

Uploadcare offers aย cloud solution for processing files that include:

  • File Uploader widget with drag-and-drop area: Uploadcare offers aย production-ready component that could beย easily integrated onto aย web page.
  • Previews: supports automatic preview generation and file type filtering.
  • On-the-fly operations: Uploadcare provides aย range ofย image optimization and transformation features, including compression, resizing, cropping, rotation, scaling, overlays, face detection, and other file types processing.
  • CDN: Aย distributed network makes itย possible for your files toย beย delivered fast across the globe.

Integrating Uploadcare File Uploader and CDN into the existing project

Toย start, letโ€™s sign up for Uploadcareโ€™s free plan and create aย sample project.

Uploadcare Project DashboardUploadcare Project Dashboard

Uploadcareโ€™s File Uploader comes inย the form ofย aย pre-configurable web-component. Follow the File Uploader link inย the Dashboard menu toย access the configuration wizard.

Uploadcareโ€™s File Uploader ConfiguratorUploadcareโ€™s File Uploader Configurator

Step 4ย ofย the configurator contains code snippets that weย need toย put onย the page.

This JSย code imports the module:

<script type="module">
  import * as UC from 'https://cdn.jsdelivr.net/npm/@uploadcare/file-uploader@v1/web/file-uploader.min.js';
  UC.defineComponents(UC);
</script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@uploadcare/file-uploader@v1/web/uc-file-uploader-regular.min.css"
/>

Hereโ€™s the styling for the widget, put itย into the CSS file:

.my-uploader {
  /* setting accent color and the of the uploader */
  --uc-primary-oklch-dark: 69% 0.1768 258.4;
  --uc-primary-oklch-light: 59% 0.22 264;

  /* positioning the uploader button on the page */
  display: inline-flex;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

Add these configuration values into the HTML file (you have your own API key placed instead of YOURPUBKEY):

<uc-config
  ctx-name="my-uploader"
  pubkey="YOURPUBKEY"
  max-local-file-size-bytes="10000000"
  img-only="true"
  source-list="local, url, camera, dropbox"
></uc-config>

Lastly, this isย the HTML code for the uploader itself:

<uc-file-uploader-regular
  ctx-name="my-uploader"
  class="my-uploader"
>
</uc-file-uploader-regular>
Uploadcare File Uploader embedded onto a pageUploadcare File Uploader embedded onto a page

Weย used the CDN installation option for simplicity. There are other options toย integrate the widget, for example into popular front-end frameworks.

Letโ€™s see how Uploadcare File Uploader implements previews:

Uploadcareโ€™s File Uploader preview functionalityUploadcareโ€™s File Uploader preview functionality

Inย the configuration step, Iย chose the โ€œImages Onlyโ€ option. Letโ€™s try uploading aย video file and see what happens:

Uploadcareโ€™s File Uploader file type restriction managementUploadcareโ€™s File Uploader file type restriction management

Uploaded files goย into your accountโ€™s storage, where you can apply further transformations and deliver them inย different formats. Uploadcare also shows the estimated file size for On-The-Fly optimization:

Uploadcareโ€™s File StorageUploadcareโ€™s File Storage

Conclusion

Weย take drag-and-drop functionality for granted these days. Asย the article shows, the process consists ofย several steps that developers should take careย of.

Try creating one yourself following this tutorial, orย simplify the process byย using Uploadcareโ€™s File Uploader and CDN toย save time and focus onย further aspects ofย developing your product.

Ready to get started?

Join developers who use Uploadcare to build fileย handling quickly andย reliably.

Sign up for free