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:

HRML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <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">
            </div>
        </div>
    </div>
</body>
</html>

CSS

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;
}

JavaScript

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

Post a Comment

Previous Post Next Post