Skip to content
Advertisement

display nothing on removing file [closed]

function previewImage() {
  var thisElement = event.target
  var file = thisElement.files;
  var fileReader = new FileReader();
  fileReader.onload = function(event) {
    thisElement.nextElementSibling.querySelector("img").setAttribute("src", event.target.result);
  }
  if (file.length) {
    fileReader.readAsDataURL(file[0])
  } else {
    fileReader.readAsDataURL()
  }
};
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="row">
  <div class="border border-dark d-flex align-items-center justify-content-center bg-warning">
    <h4 class="d-inline">PHOTO*</h4>
  </div>
</div>
<div class="row">
  <div class="border border-dark">
    <input type="file" id="file1" accept="image/*" class="form-control" onchange="previewImage();" required>
    <label for="file1" class="d-flex align-items-center justify-content-center" style="height: 170px;">
<img id="display1" class="w-100 h-100" style="cursor: pointer;">
</label><br>
  </div>
</div>

I making a form where I need to upload image & display it & it displayed. But the problem is when I remove the image then also it display the image.

Advertisement

Answer

There is no need of fileReader.readAsDataURL(); in if-else statement. Just if statement is necessary for Previewing image.

The readAsDataURL() method is used to read the contents of the specified Blob or File. Parameter is neccessary in that method. Which is missing in your else statement.

function previewImage() {
  let thisElement = event.target;
  let file = thisElement.files;
  let fileReader = new FileReader();
  let img = document.querySelector("img"); 
  fileReader.onload = function(event) {
    img.setAttribute("src", event.target.result);
  };
  if (file.length) {
    fileReader.readAsDataURL(file[0]);
  } else {
    img.src='';
  }
};
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="row">
  <div class="border border-dark d-flex align-items-center justify-content-center bg-warning">
    <h4 class="d-inline">PHOTO*</h4>
  </div>
</div>
<div class="row">
  <div class="border border-dark">
    <input type="file" id="file1" onchange="previewImage()" accept="image/*" class="form-control" required>
    <label for="file1" class="d-flex align-items-center justify-content-center" style="height: 170px;">
<img id="display1" class="w-100 h-100" style="cursor: pointer;">
</label><br>
  </div>
</div>
Advertisement