显示使用 XHR2/AJAX 下载文件的进度条

2023-05-16前端开发问题
14

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

问题描述

限时送ChatGPT账号..

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

问题是我不明白该怎么做.我编写了代码来记录进度,但不知道如何启动下载.

注意:文件属于不同类型.

提前致谢.

JS

//文件下载filelist.on('click', '.download_link', function(e){e.preventDefault();var id = $(this).data('id');$(this).parent().addClass("download_start");$.ajax({xhr: 函数 () {var xhr = 新窗口.XMLHttpRequest();//处理下载进度xhr.addEventListener("进度", function (evt) {如果(evt.lengthComputable){var percentComplete = evt.loaded/evt.total;console.log(percentComplete);}}, 错误的);返回xhr;},完成:函数(){console.log("请求完成");}})});

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">'.日期(M d,Y",$file_upload_time).' &#149;&nbsp;'.human_filesize($file_size) .'</div></div><div class="right_wing"><div 类="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="删除这个?"></i></a></div></div></li>

解决方案

如果您想向用户显示下载过程的进度条 - 您必须在 xmlhttprequest 中进行下载.这里的问题之一是,如果您的文件很大 - 它们将在浏览器将它们写入磁盘之前保存在浏览器的内存中(使用常规下载文件时直接保存到磁盘,这样可以在大文件上节省大量内存).

另一个需要注意的重要事项 - 为了使 lengthComputable 为真 - 您的服务器必须发送带有文件大小的 Content-Length 标头.

这里是javascript代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="a1" data-filename="filename.xml">点击下载</div><脚本>$('#a1').click(function() {var that = this;var page_url = 'download.php';var req = new XMLHttpRequest();req.open("POST", page_url, true);req.addEventListener("进度", function (evt) {如果(evt.lengthComputable){var percentComplete = evt.loaded/evt.total;console.log(percentComplete);}}, 错误的);req.responseType = "blob";req.onreadystatechange = function () {如果(req.readyState === 4 && req.status === 200){var filename = $(that).data('filename');if (typeof window.chrome !== 'undefined') {//铬版本var link = document.createElement('a');link.href = window.URL.createObjectURL(req.response);link.download = 文件名;链接.click();} else if (typeof window.navigator.msSaveBlob !== 'undefined') {//IE版本var blob = new Blob([req.response], { type: 'application/force-download' });window.navigator.msSaveBlob(blob, 文件名);} 别的 {//火狐版本var file = new File([req.response], filename, { type: 'application/force-download' });window.open(URL.createObjectURL(file));}}};req.send();});</脚本>

下面是你可以使用的 php 代码示例:

<块引用>

请注意,我添加了一个睡眠来模拟慢速连接以在 localhost 上进行测试.
您应该在生产中删除此 :)

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.

Thanks in advance.

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 and 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>

解决方案

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).

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.

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>

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);

Note that I added a sleep to simulate a slow connection for testing on localhost.
You should remove this on production :)

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

The End

相关推荐

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125