How to delete a photo after preview?

Asked

Viewed 135 times

-1

I have a code where I can view the photo automatically 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:

inserir a descrição da imagem aqui

The image appears correctly, but how do I so that by clicking delete, return to the default photo?

1 answer

1

Well, just take an initial image, and save that 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">

<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" onClick="restoreOriginal()">Excluir Foto</button>
</div>

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

<script>
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.