DEV Community

Cover image for Preview selected image (input type="file") using JavaScript
Michael Burrows
Michael Burrows

Posted on • Edited on • Originally published at w3collective.com

Preview selected image (input type="file") using JavaScript

*** CodePen Demo ***

By default only the file name is displayed when a user uploads an image using a file input field.

Wouldn’t it be better if the user could preview the image before continuing?

Fortunately with a little JavaScript we can display the selected image in the browser.

Let’s get started by setting up the HTML form and file upload field:

<form>
  <div>
    <div id="img-preview"></div>
    <input type="file" id="choose-file" name="choose-file" accept="image/*" />
    <label for="choose-file">Choose File</label>
  </div>
</form>
Enter fullscreen mode Exit fullscreen mode

It’s important to add "accept="image/*" so only image uploads are allowed.

Next comes the JavaScript functionality to preview the image.

Step 1 is to define variables for the input field and <div> that display’s the image.

const chooseFile = document.getElementById("choose-file");
const imgPreview = document.getElementById("img-preview");
Enter fullscreen mode Exit fullscreen mode

Step 2 is to add an event listener that detects a value change on the input field.

When this is detected we’ll call the function that get’s the image data:

chooseFile.addEventListener("change", function () {
  getImgData();
});
Enter fullscreen mode Exit fullscreen mode

The getImgSrc() function inserts an image into the page with the base64 data of the selected image:

function getImgData() {
  const files = chooseFile.files[0];
  if (files) {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(files);
    fileReader.addEventListener("load", function () {
      imgPreview.style.display = "block";
      imgPreview.innerHTML = '<img src="' + this.result + '" />';
    });    
  }
}
Enter fullscreen mode Exit fullscreen mode

Now for some CSS to contain the image size and prevent large image uploads breaking the layout:

#img-preview {
  display: none; 
  width: 155px;   
  border: 2px dashed #333;  
  margin-bottom: 20px;
}
#img-preview img {  
  width: 100%;
  height: auto; 
  display: block;   
}
Enter fullscreen mode Exit fullscreen mode

Lastly we’ll style the input field so it doesn’t look so boring:

[type="file"] {
  height: 0;  
  width: 0;
  overflow: hidden;
}
[type="file"] + label {
  font-family: sans-serif;
  background: #f44336;
  padding: 10px 30px;
  border: 2px solid #f44336;
  border-radius: 3px;
  color: #fff;
  cursor: pointer;
  transition: all 0.2s;
}
[type="file"] + label:hover {
  background-color: #fff;
  color: #f44336;
}
Enter fullscreen mode Exit fullscreen mode

Styling file fields is limited so what we’re actually doing here is hiding the field and styling the label.

This works because the file selector is also triggered when the associated label is clicked.

Top comments (0)