Jquery $ .Post百分比上传

时间:2016-05-31 12:41:57

标签: jquery ajax .post

我正在使用这个ajax方法上传图片及其中的一些数据:

$.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);
        });

这有效,但我需要一种方法来获得一定比例的上传... 抱歉英语不好,我是意大利人(:

1 个答案:

答案 0 :(得分:1)

为ajax请求使用$ .ajax,因为api定义本身有xhr。我们正在访问原生XHR请求并监听progress以显示百分比。

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);
  }
});
相关问题