jqueryajax.post

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 (:


Solution

  • Using $.ajax for ajax request since it's have xhr in api definition itself. We are accessing the 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({
      xhr: function()
        {
        var xhr = new window.XMLHttpRequest();
        //Upload progress
        xhr.upload.addEventListener("progress", function(evt){
          if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            //Do something with upload progress
            console.log(percentComplete);
          }
        }, false);
        //Download progress
        xhr.addEventListener("progress", function(evt){
          if (evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            //Do something with download progress
            console.log(percentComplete);
          }
        }, false);
        return xhr;
      },
      type: 'POST',
      url: "/",
      data: data,
      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);
      }
    });