Photo upload automatically with Jquery

Asked

Viewed 26 times

0

I have a form where the photo appears as a preview when selected for upload:

inserir a descrição da imagem aqui

I would like when selecting the photo to upload automatically. How I would pass the values to the page alter-photo.php?

The code goes below:

<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: -10px" onclick="excluirImagem()">Excluir Foto</button>
</div>
<input type="file" name="FotoPerfil" id="imagem" onchange="previewImagem()">
<div>    

    <script>
    function previewImagem(){

      var input = document.getElementById("imagem");
      var nome = input.files[0].name;
      var extensao = nome.split('.').pop();

      if(extensao != 'jpeg' && extensao != 'jpg' && extensao != 'png'){
         $('#acessar').modal('show');
      }else{
        var imagem = document.querySelector('input[name=FotoPerfil]').files[0];
        var preview = document.querySelector('img');
        var reader = new FileReader();

        var data = new FormData();
        data.append('FotoPerfil', $('#imagem')[0].files[0]);

        $.ajax({
            url: 'alterar-foto-perfil.php',
            data: data,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function(data)
            {
                alert(data);
            }
        });

        reader.onloadend = function () {
            preview.src = reader.result;
        }
        if(imagem){
            reader.readAsDataURL(imagem);
        }else{
            preview.src = "";
        }
    }
  }
    function excluirImagem(){
         var preview = document.querySelector('img');
         preview.src = "img/foto_usuario.png";
    }
</script>

When using the above code, it returns me value 0.

  • Hello Ricardo, I did as the link indicated, but did not solve. I changed my post adapting the code snippet.

  • Utilize data.append('FotoPerfil', $('#imagem')[0].prop('files')[0]);

  • Hello Valdeir. I did so, but when I do, the image no longer appears in the preview and is not uploaded.

No answers

Browser other questions tagged

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