alex alex - 6 months ago 34
Ajax Question

Jquery $.Post percentage upload

i'm using this ajax method for upload an image and some data of that :

$.post("http://-------/uploadFile",{
img: $("#imageDaRitagliare").cropper('getCroppedCanvas').toDataURL(),
nomeFile : nomeFileInUso,
nomeFileOrigin : nomeOriginaleFileInUso,
fileAttuale : $("#img_input").attr("nomeFile"),
fileAttualePath : $("#img_input").attr("pathfile"),
fileCanellaAttuale : canCanc
},function(response){
var dato = JSON.parse(response);

$("#img_input").empty().val(dato.nomeOriginaleFile);
$("#img_input").attr("nomeFile",dato.nomeFile);
$("#img_input").attr("pathFile",dato.path);
});


this works but i need a way to have a percentage of the upload...
sorry for bad english, i'm italian (:

Answer

Using $.ajax for ajax request since it's have beforeSend in api definition itself. We are accessing teh native XHR request and listening for progress to show percentage.

var data = {
        img:$("#imageDaRitagliare").cropper('getCroppedCanvas').toDataURL(),
        nomeFile : nomeFileInUso,
        nomeFileOrigin : nomeOriginaleFileInUso,
        fileAttuale : $("#img_input").attr("nomeFile"),
        fileAttualePath : $("#img_input").attr("pathfile"),
        fileCanellaAttuale : canCanc
    }

$.ajax({
  type: 'POST',
  url: "/",
  data: data,
  beforeSend: function(XMLHttpRequest)
  {
    //Upload progress
    XMLHttpRequest.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {  
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
      }
    }, false); 
    //Download progress
    XMLHttpRequest.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {  
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
      }
    }, false); 
  },
  success: function(response){
     var dato = JSON.parse(response);

        $("#img_input").empty().val(dato.nomeOriginaleFile);
        $("#img_input").attr("nomeFile",dato.nomeFile);
        $("#img_input").attr("pathFile",dato.path);
  }
});