显示使用XHR2 / AJAX下载文件的进度条 [英] Show a progress bar for downloading files using XHR2/AJAX

查看:182
本文介绍了显示使用XHR2 / AJAX下载文件的进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Ajax下载文件并显示自定义下载进度条。

I am trying to download files using Ajax and show a custom download progress bar.

问题是我无法理解这样做。我编写了代码来记录进度,但不知道如何启动下载。

The problem is I can't understand how to do so. I wrote the code to log the progress but don't know how to initiate the download.

注意:这些文件的类型不同。

NOTE: The files are of different types.

提前致谢。

JS

// Downloading of files
filelist.on('click', '.download_link', function(e){
    e.preventDefault();
    var id = $(this).data('id');
    $(this).parent().addClass("download_start");

    $.ajax({
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            // Handle Download Progress
            xhr.addEventListener("progress", function (evt) {
                if(evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    console.log(percentComplete);
                }
            }, false);
            return xhr;
        },
        complete: function () {
            console.log("Request finished");
        }
    })
});

HTML和PHP

    <li>
    <div class="f_icon"><img src="' . $ico_path . '"></div>
    <div class="left_wing">
       <div class="progressbar"></div>
       <a class="download_link" href="#" id="'.$file_id.'"><div class="f_name">' . $full_file_name . '</div></a>
       <div class="f_time_size">' . date("M d, Y", $file_upload_time) . '&nbsp; &#149; &nbsp;' . human_filesize($file_size) . '</div>
    </div>

    <div class="right_wing">
       <div class="f_delete">
       <a class="btn btn-danger" href="#" aria-label="Delete" data-id="'.$file_id.'" data-filename="'.$full_file_name.'"><i class="fa fa-trash-o fa-lg" aria-hidden="true" title="Delete this?"></i>
       </a>
    </div>
   </div>
    </li>


推荐答案

如果要向用户显示进度条下载过程 - 您必须在xmlhttprequest中进行下载。这里的一个问题是,如果你的文件很大 - 它们将被保存在浏览器的内容中,然后浏览器将它们写入磁盘(当使用常规下载文件时直接保存)到磁盘上,这会在大文件上节省大量内存。)

If you want to show the user a progress-bar of the downloading process - you must do the download within the xmlhttprequest. One of the problems here is that if your files are big - they will be saved in the memory of the browser before the browser will write them to the disk (when using the regular download files are being saved directly to the disk, which saves a lot of memory on big files).

另一个需要注意的重要事项 - 为了 lengthComputable 为真 - 你的服务器必须发送带文件大小的 Content-Length 标题。

Another important thing to note - in order for the lengthComputable to be true - your server must send the Content-Length header with the size of the file.

这是javascript代码:

Here is the javascript code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1" data-filename="filename.xml">Click to download</div>
<script>
$('#a1').click(function() {
    var that = this;
    var page_url = 'download.php';

    var req = new XMLHttpRequest();
    req.open("POST", page_url, true);
    req.addEventListener("progress", function (evt) {
        if(evt.lengthComputable) {
            var percentComplete = evt.loaded / evt.total;
            console.log(percentComplete);
        }
    }, false);

    req.responseType = "blob";
    req.onreadystatechange = function () {
        if (req.readyState === 4 && req.status === 200) {
            var filename = $(that).data('filename');
            if (typeof window.chrome !== 'undefined') {
                // Chrome version
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(req.response);
                link.download = filename;
                link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE version
                var blob = new Blob([req.response], { type: 'application/force-download' });
                window.navigator.msSaveBlob(blob, filename);
            } else {
                // Firefox version
                var file = new File([req.response], filename, { type: 'application/force-download' });
                window.open(URL.createObjectURL(file));
            }
        }
    };
    req.send();
});
</script>

以下是您可以使用的PHP代码示例:

And here is an example for the php code you can use:

<?php
$filename = "some-big-file";
$filesize = filesize($filename);

header("Content-Transfer-Encoding: Binary");
header("Content-Length:". $filesize);
header("Content-Disposition: attachment");

$handle = fopen($filename, "rb");
if (FALSE === $handle) {
    exit("Failed to open stream to URL");
}

while (!feof($handle)) {
    echo fread($handle, 1024*1024*10);
    sleep(3);
}

fclose($handle);




请注意,我添加了一个睡眠以模拟慢速连接以进行测试localhost。

您应该删除此生产:)

这篇关于显示使用XHR2 / AJAX下载文件的进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆