DEV Community

Cover image for Drag and drop to upload a photo #JavaScript #CSS
İnanç Akduvan
İnanç Akduvan

Posted on • Edited on

1

Drag and drop to upload a photo #JavaScript #CSS

We will create a very basic drag and drop application to upload a image.

1.a) Create an area to drop image

<div class="drop-container">
      <span>Drop image here to upload</span>
</div>

<div id="file_name">You haven't uploaded a photo yet.</div>
Enter fullscreen mode Exit fullscreen mode

1.b) And add a little bit style

.drop-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px;
    min-height: 400px;
    width: 100%;
    max-width: 600px;
    font-size: 1.5rem;
    border: 2px dashed rgb(255, 203, 232);
    border-radius: 8px;
}

.drop-container.uploaded {
    border-color: #51cbb0;
    border-style: solid;
}

.drop-container img {
    max-width: 100%;
}

#file_name {
    margin-top: 32px;
}
Enter fullscreen mode Exit fullscreen mode

It will look like:
Image description

2) Prevent default behaviour of 'dragover' event
Otherwise, image which is dropped will be opened in a blank tab.

const dropContainer = document.querySelector(".drop-container");

dropContainer.addEventListener("dragover", (event) => {
  event.preventDefault();
});
Enter fullscreen mode Exit fullscreen mode

3) Get file on drop
We also need to prevent default behaviour here.

const dropContainer = document.querySelector(".drop-container");
const fileName = document.getElementById("file_name");

dropContainer.addEventListener("dragover", (event) => {
  event.preventDefault();
});

dropContainer.addEventListener("drop", (event) => {
  event.preventDefault();

  // Get file uploaded
  const file = event.dataTransfer.files[0];

  console.log(file)
});
Enter fullscreen mode Exit fullscreen mode

4) Preview image which we uploaded
We will create a link for the file and preview it as a image.

const dropContainer = document.querySelector(".drop-container");
const fileName = document.getElementById("file_name");

dropContainer.addEventListener("dragover", (event) => {
  event.preventDefault();
});

dropContainer.addEventListener("drop", (event) => {
  event.preventDefault();

  // Get file
  const file = event.dataTransfer.files[0];

  // Create link
  const url = window.URL.createObjectURL(file);

  // Create image element
  const image = document.createElement("img");
  image.src = url;

  // Append image as a child to drop area
  dropContainer.innerHTML = "";
  dropContainer.appendChild(image);

  // Add class to drop container when image uploaded  
  // for updating styles
  dropContainer.classList.add("uploaded");

  // Preview file name and type
  fileName.innerHTML = `${file.name} [${file.type}]`;
});
Enter fullscreen mode Exit fullscreen mode

Here it is. 🎉

Image description

5) EXTRA PART
Check if the file type is image or not

const dropContainer = document.querySelector(".drop-container");
const fileName = document.getElementById("file_name");

dropContainer.addEventListener("dragover", (event) => {
  event.preventDefault();
});

dropContainer.addEventListener("drop", (event) => {
  event.preventDefault();

  let file;

  if (event.dataTransfer.items) {
    const item = event.dataTransfer.items[0];

    const isFile = item.kind === "file";
    const isImage = item.type.split("/")[0] === "image";

    if (isFile && isImage) {
      file = item.getAsFile();
    } else {
      alert("This is not an image!");

      return;
    }
  } else {
    file = event.dataTransfer.files[0];
  }

  const url = window.URL.createObjectURL(file);

  const image = document.createElement("img");
  image.src = url;

  dropContainer.innerHTML = "";
  dropContainer.appendChild(image);

  dropContainer.classList.add("uploaded");

  fileName.innerHTML = `${file.name} [${file.type}]`;
});
Enter fullscreen mode Exit fullscreen mode

That is it. Find source code on github:
https://github.com/inancakduvan/drag-and-drop-image


Follow me on:

Github: https://github.com/inancakduvan/
Twitter: https://twitter.com/InancAkduvan

Thank you for reading 🙂

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay