使用下载进度条JQuery跟踪下载文件?

时间:2018-04-14 04:19:13

标签: jquery jquery-ui jquery-plugins

提供下载手动按钮。点击这些按钮,应下载超过5 MB的pdf文件。应显示进度条以显示已下载文件的百分比。下载完成后,进度条应达到100%,应隐藏。应显示弹出消息“下载完成”。 使用JQuery。

2 个答案:

答案 0 :(得分:2)

 <script type="text/javascript">
    $(".download").click(function(){
    window.location.href = 'file/30mb.pdf'; //set your file url which want to download
    var data = [];
    for (var i = 0; i < 100000; i++) {
    var tmp = [];
    for (var i = 0; i < 100000; i++) {
    tmp[i] = 'hue';
    }
    data[i] = tmp;
    };
    $.ajax({
    xhr: function () {
    var xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) {
    if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    //console.log(percentComplete);
    $('.progress').css({
    width: percentComplete * 100 + '%'
    });
    if (percentComplete === 1) {
    $('.progress').addClass('hide');
    }
    }
    }, false);
    xhr.addEventListener("progress", function (evt) {
    if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    console.log(Math.round(percentComplete*100)+"%");
    $(".perc").text(Math.round(percentComplete*100)+"%");
    if((Math.round(percentComplete*100))==100)
    {
    $(".perc").text("download completed");
    $('.progress').removeClass('hide');
    // $(".perc").text("");
    }
    $('.progress').css({
    width: percentComplete * 100 + '%'
    });
    }
    }, false);
    return xhr;
    },
    type: 'POST',
    url: "file/30mb.pdf", //set your file url which want to download
    data: data,
    success: function (data) {}
    });
    });

    </script>

Output

https://jsfiddle.net/viralvanani/x2uhyjjL/

答案 1 :(得分:0)

您可以使用ajax-progress等插件。

我在jsfiddle

上创建了一个小型复制
const url = '//somefile.pdf'

$.ajax(url, {
  progress: function(e) {
    if (e.lengthComputable) {
      const completedPercentage = Math.round((e.loaded * 100) / e.total);
      // You can inject completedPercentage into the DOM now
      console.log(completedPercentage);
    }
  }
})

请注意,您放置的网址必须可由您的域访问(即应设置Access-Control-Allow-Origin)。