Popular Posts

Preview Image Before Upload using HTML, CSS & JavaScript

There are many ways to achieve this. The most efficient way would be to use URL.createObjectURL() on the image file from your <input> element. Pass this URL to img.src to tell the browser to load the selected image.



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