Skip to main content

The Ultimate Guide to Drag and Drop Image Uploading with Pure JavaScript

In this guide, I’ll be explaining how to upload images by dragging and dropping. This includes dragging images
  1. From OS to browser
  2. From browser to browser
I’ll be using Pure Javascript (no frameworks or libraries), and the code will be compatible with all modern browsers including IE 9+. Also, I haven’t used ES6 which means you won’t need a compiler like Babel to run the code.
Our Drag & Drop function will do 5 things.
  1. Listen for drag and drop
  2. Indicate when a file is hovering on the drop region
  3. Validate dropped images
  4. Preview images
  5. Upload images
However, relying completely on drag & drop is a bad idea because mobile users won’t like it. Also, most mobile browsers don’t even support the API. Here’s the browser support for Drag & Drop API from caniuse.com.
the browser support for Drag & Drop API
the browser support for Drag & Drop API
Therefore, we will also allow users to simply upload files by selecting them (Via <input type="file").
Here’s the final result of this tutorial:
The Final Result
A demo is available on JSFiddle
Let’s start with basic HTML.

Then, save the elements in Javascript variables.

File Selector

For file selecting, we have to use <input type="file"> here. However, those default file selectors look old-fashioned and hard to style with CSS. Therefore, using fake file input, we can make dropRegoin opening the file selector when clicked.

Note that the accept attribute (fakeInput.accept = "image/*") is used to limit the files to image files. You can also specify the mime type too. For example, if you only need users to select only GIF files, you can use image/gif. Or, multiple values like image/png, image/jpeg. The multiple attribute allows users to select multiple images at once.
Now, when the dropRegion is clicked, the fakeInput will be clicked. So, the browser will open the OS file selector.
Let’s add the onChange event to the file input.

fakeInput.files is a FileList which we can use to preview and upload images. We will create the handleFiles() function later.

Drag Events

The Drag & Drop API defines 8 events: 4 events for the draggable element and 4 events for the droppable element. We will only need the latter 4 when developing a drag & drop image uploading.
  • dragenter: a dragged item enters a valid drop target.
  • dragleave: a dragged item leaves a valid drop target.
  • dragover: a dragged item is being dragged over a valid drop target. Triggered every few hundred milliseconds.
  • drop: an item is dropped on a valid drop target.

Adding Drag & Drop Functionality

When a file is dragged into the browser from the OS, the browser will try to open and display it by default. We have to prevent default behaviors and stop propagating to upper elements for all the events. This ensures any external event (especially an event of an outer element) doesn’t crash the functionality.

Then, we can handle the drop event.

e.dataTransfer is a Data Transfer object which contains the dragged data. e.dataTransfer.filescontains the dragged local files as a FileList which is exactly same as the files variable in the change event handler of the file input.
Now it’s the time to create the handleFiles() function which gets a File List and upload each item.

We can loop through the FileList (files here) using a simple for loop. If each file is a valid image, we will preview and upload it.
Wait! There’s a problem. This only works if the files are dragged from the local file system. What if an image is dragged from another webpage? We will need to optimize our drop handler for this (This is quite tricky).
Here’s the upgraded handleDrop function.

Here if files are not selected, we will check for browser images. When you drag an image on the browser to another place, the image is dragged as HTML. So, we can get the HTML and check for src="" attribute which is the image URL. Then, we can fetch the image with Image object and convert it to a canvas. Finally, the canvas can be converted to a blob, and we can use our handleFiles function as usual.
However, there some limitations to this implementation. This would not work if the image is from a server that blocks cross-domain requests. To solve that, you can use a proxy image server to fetch images. And, also dragging from chrome to firefox can also show errors. Even with those limitations, dragging from one page to another is a cool feature.

Validating Images


This function validates two attributes.
  1. File type – In this example, I have allowed jpg, png, and gif files. However, you can add or remove any valid MIME type.
2. File size – I have set the maximum size to 10MB. It is a good practice to limit the file size to prevent malicious oversized uploading.
Validating on the client-side has one advantage. The user can know instantly whether their image is valid. If we completely rely on server-side validation, the user has to wait until the upload is finished and the server processes the response. This can be a burden for the server if the image files are very large.
(Validating file size from the client-side inadequate. You must validate it again on the server-side.)

Previewing and Uploading Images

1. Previewing

There are several ways to preview the image.
  1. Preview after uploading – Upload the image, get the image URL, and display it.
  2. Preview before uploading – We can preview the image before uploading. This is fast and efficient. There are two Javascript methods we can use.
    1. URL.createObjectURL()
    2. FileReader.readAsDataURL()
For this example, I’ll choose 2.2: Preview the image before uploading using FileReader.readAsDataURL().
Let’s start

We will read the image in the next step and display it on img element. The overlay will be used to add a faded look to each image until uploaded. We will reduce the width of the overlay when the image is uploading.
Let’s read the image and preview.

Here we create a FileReader object and set up the onload event handler for it. Then, we read the image as a data URL. This is done asynchronously. After the reading is finished, the onload callback will be called. The src attribute of the img element will be set to e.target.result which is a base64 data URL.

2. Uploading

We can use FormData interface to create form data to send them to the server. Then, we can use AJAX with XMLHttpRequest to perform an asynchronous upload.
Creating form data:

AJAX request:

Here uploadLocation should be set to the server URL of the upload handler. The onreadystatechangeevent handler is called when the state is changed. ajax.readyState is 4 when the request is completed. ajax.status is the status code sent by the server. Usually, servers set the status code to 200 when the request is successful. ajax.upload.onprogress event handler is called each time when the progress is updated. In this function, we calculate the percentage of the progress and reduce that from the overlay’s width.
And, the || 100 part is a simple bug fix. Sometimes, (e.loaded / e.total * 100) can return NaN. In that case, the default value, 100, will be used.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...