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.files contains 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 onreadystatechange event 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.

Here’s the complete function.


Finally, here’s the CSS I created. You can change it as you like.

Additional Improvements

1. Detect drag & drop feature and change the message

It is not useful to show the message “Drag & Drop images or click to upload” on browsers which don’t support the Drag and Drop API. So, we can detect the feature and change the message.

Detect function is taken from Modernizr.

2. Highlight on dragenter

We can highlight the dropRegion when a file is dragging over using the drag events.


Then, some CSS for .highlighted will make the dropRegion more interesting. For example,

Conclusion

In this article, I described how to upload a file using drag and drop. It is true that some effort is needed to create a drag and drop functionality. However, if you use a library like jquery the DOM manipulation would be much easier even the process is the same. If you need it, you can use ES6 and make syntax shorter. The fetch() API can also be instead of XMLHttpRequest. Finally, check out and play with the JSFiddle I created. I used the free service IMGBB for image uploading.

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

13.02.2020

JavaScript find() and filter() Array Iteration Methods Made Easy

While this article will be more focused on making you understand these two array iteration methods, it will also create a fun, interesting and easy ...

Dockerization of Node.JS Applications on Amazon Elastic Containers

This article is about creating a critical task-based highly available and scalable NodeJS application on the Amazon Cloud with an architecture that ...

How I Got Started with Angular and TypeScript

I share my experience on how to learn the most basic parts of Angular and ...

2 comments

Nikita Bragin December 28, 2019 at 1:44 pm
1

 Supun Kavinda , commonly I used libraries for Drag & Drop, really helpful to know how to realize it on pure JS!

 
Supun Kavinda December 28, 2019 at 5:09 pm
2

 I’m really happy to hear that 🙂

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy