Preview Image Before Upload in JavaScript

Preview Image Before Upload in JavaScript
Project: Preview Image Before Upload
Author: Abiodun Emmanuel
Edit Online: View on CodePen
License: MIT

This simple JavaScript code snippet helps you to create image preview functionality before upload to the server. It reads the selected image file and converts it into a data URL using the FileReader API or alternatively, using URL.createObjectURL method.

It then sets the source of the image element with the data URL, which automatically displays the selected image in the preview area. The ‘show’ class is added to the image container to ensure the preview is visible.

How to Create Preview Image Feature Before Upload using JavaScript

1. Create the HTML structure with a ‘form’ class containing an image element (‘img_preview’) and an input element (‘img_input’) of type ‘file’ with the ‘accept’ attribute set to ‘image/*’. Add the ‘onchange’ attribute to the input element, calling the ‘showImage()’ function.

<div class='form'>
  <img id="img_preview" src="" alt="">
  <input id="img_input" type="file" accept='image/*' onchange="showImage()">
</div>

2. Apply CSS styles to style the preview container and the image. You can define CSS rules according to your web/app template.

.form {
  display: flex;
  justify-content: center;
    flex-direction: column;
  flex-wrap: wrap;
  text-align: center;
  align-content: center;
}

img {
  width: 100%;
  max-width: 300px;
  border: 1px solid #ccc;
  box-shadow: 0px 3px 8px #ccc;
  border-radius: 5px;
  padding: 4px;
  display: none;
}
img.show {
  display: block;
}

input {
  width: 100%;
}

3. Finally, add the following JavaScript function to your project to preview image before upload.

const imageUploader = document.querySelector("#img_input");
const imagePreview = document.querySelector("#img_preview");

function showImage() {
  let reader = new FileReader();
 reader.readAsDataURL(imageUploader.files[0]);
  reader.onload = function(e) {
    imagePreview.classList.add("show");
    imagePreview.src = e.target.result;
  };
}

// OR

// function showImage() {
//   const file = imageUploader.files[0];
//     imagePreview.classList.add("show");
//     imagePreview.src = URL.createObjectURL(file);
// }

Use the ‘imageUploader’ variable to select the ‘img_input’ element and ‘imagePreview’ to select the ‘img_preview’ element. The ‘showImage()’ function creates a FileReader object, reads the selected image file, and then sets the source of the ‘img_preview’ element with the data URL to display the preview.

That’s all! hopefully, you have successfully integrated this image preview functionality to your project. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply