Automatic image upload without refresh

1

Colleagues.

I want to implement an image update on my system, as it happens on facebook, where we click on the existing image and select the desired image from our computer and the image is automatically updated without the need to push a button.

I found the code below, which I can click on a link to upload, but I can not finish. Could someone help me?

HTML

<div class='atualiza'><img src='imagematual.jpg'></div>

<input id="upload" type="file"> 
<a h ref="" id="upload_link">Alterar foto</a>

I separated the h ref, because in the view here interpreted as html

CSS

 #upload_link{ 
text-decoration:none; 
} 
#upload{ 
display:none 
} 

JQUERY

$(function(){ 
            $("#upload_link").on('click', function(e){ 
            e.preventDefault(); 
            $("#upload:hidden").trigger('click'); 
            // Não sei cmo passar a foto para a página upload.php
             $.ajax({url: "upload.php?foto=", success: function(result){
           // Não sei como faria para que a imagem atualizasse sem refresh          
            $("#atualiza").html(result);
          }});
         }); 
        }); 
    
asked by anonymous 24.10.2016 / 14:57

1 answer

1

First step, to send a file via ajax, you need to disable the default behavior of jQuery ( application/x-www-form-urlencoded ) and use the web standard ( multipart/form-data ).

$.ajax({
  url: form.action,
  data: data,
  contentType: false, // evitar que o jQuery realize o set do 'content-type' para 'application/x-www-form-urlencoded'.
  processData: false, // evitar que o jQuery tente serialzar o conteudo usando o $.params().
  type: form.method,
  success: function(data){
    console.log(data);
  }
});

Now let's go to the form.:

var form = $("#formUpload")[0];
var enviar = $("#Enviar");
enviar.on("click", function (event) {
  var data = new FormData(form);
  $.ajax({
    url: form.action,
    data: data,
    contentType: false,
    processData: false,
    type: form.method,
    success: function(data){
      console.log(data);
    }
  });
  return false;
});
<form id="formUpload">
  <div>
    <label>
      Descrição:
      <input type="text" id="Descricao" name="Descricao" value="" />
    </label>
  </div>
  <div>
    <label>
      Arquivo
      <input type="file" id="Arquivo" name="Arquivo" value="" />
    </label>
  </div>
  <div>
    <input type="submit" id="Enviar" name="Enviar" value="Enviar" />
  </div>
</form>

Now if you do not have a form and want to upload it as soon as the user selects a file.:

var arquivo = $("#Arquivo");
arquivo.on("change", function (event) {
  if (arquivo[0].files.length == 0)
    return false;
  
  var data = new FormData();
  data.append('Arquivo', arquivo[0].files[0]); 
  $.ajax({
    url: "minha url",
    data: data,
    contentType: false,
    processData: false,
    type: "POST",
    success: function(data){
      console.log(data);
    }
  });
  return false;
});
<input type="file" id="Arquivo" name="Arquivo" value="" />

Finally, extra information that can be useful to you, you can create a link to objects in memory, then you can create a link to the selected image and already update your image without making a AJAX request.

This technique can be useful for the user to preview the image before uploading.

var arquivo = $("#arquivo");
var imagem = $("#imagem");

arquivo.on("change", function () {
  if (arquivo[0].files.length == 0)
    return false;
  
  var file = arquivo[0].files[0];
  var url = URL.createObjectURL(file);
  imagem.attr("src", url);
  imagem.attr("title", file.name);
  console.log(arquivo[0].files[0]);
});
#imagem {
  width: 480px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="file" id="arquivo" name="arquivo" />
<br />
<img id="imagem" src="#" title="" />
    
24.10.2016 / 15:11