avatarMiguel Z. Nunez

Summary

This tutorial provides a step-by-step guide on how to upload and preview images on the frontend using JavaScript.

Abstract

The article is a comprehensive tutorial that teaches users how to implement an image upload feature on a web page using JavaScript. It covers the process of creating an input field for file selection, handling the upload event, storing the selected images in an array, and displaying them on the screen. The guide also includes instructions on how to create a function to delete images from the display and the array, as well as basic CSS styling for the image display. The tutorial emphasizes uploading single images and provides links to additional resources for handling multiple image uploads and server-side uploading with Node.js and Multer.

Opinions

  • The author suggests that handling single image uploads is simpler and provides a focused guide for this scenario.
  • The author expresses the ease of creating object URLs for images using the URL.createObjectURL method.
  • The guide encourages customization of the CSS to suit individual design preferences.
  • The author promotes their other tutorials, implying that they provide value and extend the capabilities of image uploading systems.
  • By mentioning the "best image uploading system tutorial on the internet," the author conveys confidence in the quality and comprehensiveness of their instructional content.

How to Upload and Preview Images — JavaScript

A step by step guide on uploading images on the frontend

How to upload and display images? You’ve come to the right place. In this tutorial, I’ll teach you how to do this easily with JavaScript. Before we start, I want to point out that this guide only shows you how to upload one image at a time. If you want to learn how to upload multiple images at a time, you can read this guide and if you want to learn how to upload and save images (so they’re still there when you click the refresh button), you can read this guide.

In this guide, you’ll learn how to build the following app:

How to Upload and Preview Images with JavaScript

Let’s get started.

HTML:

Create an input field of type file with an accept attribute that indicates the image file types you want to accept. I went ahead and accepted the following: JPEG, PNG, and JPG. The purpose of the output element is simply to act as a container that displays the images.

<input type="file" accept="image/jpeg, image/png, image/jpg">
<output></output>

JavaScript:

Access the input and output elements by initializing them to their own respective variable, input and output. Also create an array named imagesArray to store the images.

const input = document.querySelector("input")
const output = document.querySelector("output")
let imagesArray = []

Attach a change event to the input field so it can detect whenever the user uploads an image.

input.addEventListener("change", function() {

  
})

Every time they do, access the image through input.files and store it in a variable named file.

input.addEventListener("change", () => {
   const file = input.files
})

Push the file into the imagesArray.

input.addEventListener("change", () => {
  const file = input.files
  imagesArray.push(file[0])
})

Make a function call to displayImages, a function that displays the images on the screen. We’ll build the actual function in the next step.

input.addEventListener("change", () => {
  const file = input.files
  imagesArray.push(file[0])
  displayImages()
})

Let’s build the displayImages function now. Inside, create a variable named images that holds the dynamic HTML for each image.

function displayImages() {
  let images = ""
}

Now traverse the imagesArray by using forEach.

function displayImages() {
  let images = ""
  imagesArray.forEach((image, index) => {
    
  })
}

For each image, create a div with a class name of image and a img tag that holds the URL for the image. Creating a URL for an image is easy, just pass the image as a parameter into URL.createObjectURL. Also create a function named deleteImage that removes the image from the screen.

function displayImages() {
  let images = ""
  imagesArray.forEach((image, index) => {
    images += `<div class="image">
                <img src="${URL.createObjectURL(image)}" alt="image">
                <span onclick="deleteImage(${index})">&times;</span>
              </div>`
  })
}

Now set the innerHTML of the output element to the images variable. This will display the images on the screen.

function displayImages() {
  let images = ""
  imagesArray.forEach((image, index) => {
    images += `<div class="image">
                <img src="${URL.createObjectURL(image)}" alt="image">
                <span onclick="deleteImage(${index})">&times;</span>
              </div>`
  })
  output.innerHTML = images
}

We’re almost done, we just need to complete the deleteImage function. Notice that we have index coming in as a parameter, use it to remove the respective image from the imagesArray and call on the displayImages function to display the updated images on the screen.

function deleteImage(index) {
  imagesArray.splice(index, 1)
  displayImages()
}

CSS:

I won’t dive into what each line of code of CSS is doing as it merely acts as the design but feel free to customize this to your liking.

output{
  width: 100%;
  min-height: 150px;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 15px;
  position: relative;
  border-radius: 5px;
}

output .image{
  height: 150px;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  position: relative;
}

output .image img{
  height: 100%;
  width: 100%;
}

output .image span {
  position: absolute;
  top: -4px;
  right: 4px;
  cursor: pointer;
  font-size: 22px;
  color: white;
}

output .image span:hover {
  opacity: 0.8;
}

output .span--hidden{
  visibility: hidden;
}

Like this story? Applaud and comment below. Also don’t forget to check out my other stories related to uploading images with JavaScript.

How to Upload and Preview Multiple Images — JavaScript

How to Drag & Drop Images — JavaScript

How to Upload Images to a Server with Node.js and Multer — JavaScript

…. or watch the best image uploading system tutorial on the internet below.

Javascript Tips
Javascript Events
Upload Photo Javascript
Coding
Input Field
Recommended from ReadMedium