How to delete a photo after the preview?

-1

I have a code where I can automatically view the photo after selecting it for upload. See:

 <img class="img-fluid" style="width: 278px; height: 255px">

<div class="faq-profile-btn">
    <label for="imagem" class="btn btn-primary waves-effect waves-light">Nova Foto</label>
    <button type="button" class="btn btn-danger waves-effect waves-light" style="margin-top: -8px">Excluir Foto</button>
</div>

<input type="file" name="imagem" id="imagem" onchange="previewImagem()">

<script>
    function previewImagem(){
        var imagem = document.querySelector('input[name=imagem]').files[0];
        var preview = document.querySelector('img');

        var reader = new FileReader();

        reader.onloadend = function () {
            preview.src = reader.result;
        }

        if(imagem){
            reader.readAsDataURL(imagem);
        }else{
            preview.src = "";
        }
    }
</script>

As a result:

The image appears correctly, but how do I, when I click delete, go back to the default photo?

    
asked by anonymous 13.09.2018 / 16:12

1 answer

1

Well, you just have an initial image, and save this value to restore when you click the delete button ...

var profilePic = null;

function previewImagem() {
  var imagem = document.querySelector('input[name=imagem]').files[0];
  var preview = document.querySelector('img');
  
  //Guardando a imagem inicial
  if(profilePic == null)
    profilePic = preview.src;

  var reader = new FileReader();

  reader.onloadend = function() {
    preview.src = reader.result;
  }

  if (imagem) {
    reader.readAsDataURL(imagem);
  } else {
    preview.src = "";
  }
}

function restoreOriginal(){
  var preview = document.querySelector('img');
  
  //Limpando a seleção do arquivo
  document.querySelector('input[name=imagem]').value = "";
  
  //Restaurando a imagem inicial
  if(profilePic != null)
    preview.src = profilePic
    
}
<img class="img-fluid" style="width: 278px; height: 255px" src="https://i.stack.imgur.com/Nwv27.png"><divclass="faq-profile-btn">
  <label for="imagem" class="btn btn-primary waves-effect waves-light">Nova Foto</label>
  <button type="button" class="btn btn-danger waves-effect waves-light" style="margin-top: -8px" onClick="restoreOriginal()">Excluir Foto</button>
</div>

<input type="file" name="imagem" id="imagem" onchange="previewImagem()">

<script>
</script>
    
03.01.2019 / 13:35