Cambo ITs

How to Preview an Image Before Upload using JavaScript

    In this article, I will show you how you can preview an image before it is uploaded to the server. To Preview images before uploading I have used HTML CSS and JavaScript. There are many ways to achieve this. The most efficient way would be to use URL.createObjectURL() the image file from your <input> element. Pass this URL to img.src to tell the browser to load the selected image.

Source Code:


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <div class="center">
        <div class="form-input">
            <label for="file-ip-1">Upload Image</label>
            <input type="file" id="file-ip-1" accept="image/*" onchange="showPreview(event);">
            <div class="preview">
                <img id="file-ip-1-preview">


body {
     margin: 0px;
     height: 100vh;
     background: #333;
.center {
     height: 100%;
     display: flex;
     align-items: center;
     justify-content: center;
.form-input {
     width: 250px;
     padding: 20px;
     background: #fff;
     border: 2px dashed #555;
.form-input input {
     display: none;
.form-input label {
     display: block;
     width: 100%;
     height: 50px;
     line-height: 50px;
     text-align: center;
     background: #333;
     color: #fff;
     font-size: 15px;
     font-family: "Open Sans", sans-serif;
     text-transform: Uppercase;
     font-weight: 600;
     border-radius: 10px;
     cursor: pointer;
.form-input img {
     width: 100%;
     display: none;
     margin-top: 10px;


function showPreview(event){
  if( > 0){
    var src = URL.createObjectURL([0]);
    var preview = document.getElementById("file-ip-1-preview");
    preview.src = src; = "block";

Post a Comment

Previous Post Next Post