2024年03月23日 PHP下载进度条 PHP怎么获取下载进度 PHP实现下载进度条 懒猪技术
download.php
<?php
// 当前文件:download.php
$action = @$_GET@['action'];
// 自己获取这些信息
$remote_url = get_remote_file_url();
$file_size = get_remote_file_size($remote_url);
$tmp_path = get_tmp_path();
switch ($action) {
case 'prepare-download':
// 下载缓存文件夹
$download_cache = __DIR__."/download_cache";
if (!($download_cache)) {
if (false === ($download_cache)) {
exit('创建下载缓存文件夹失败,请检查目录权限。');
}
}
$tmp_path = $download_cache."/update_".().".zip";
save_tmp_path(); // 这里保存临时文件地址
return json(('remote_url', 'tmp_path', 'file_size'));
break;
case 'start-download':
// 这里检测下 tmp_path 是否存在
try {
(0);
($tmp_path);
// 做些日志处理
if ($fp = ($remote_url, "rb")) {
if (!$download_fp = ($tmp_path, "wb")) {
exit;
}
while (!($fp)) {
if (!($tmp_path)) {
// 如果临时文件被删除就取消下载
($download_fp);
exit;
}
($download_fp, ($fp, 1024 * 8 ), 1024 * 8);
}
($download_fp);
($fp);
} else {
exit;
}
} catch (Exception $e) {
Storage::remove($tmp_path);
exit('发生错误:'.$e->getMessage());
}
return json(('tmp_path'));
break;
case 'get-file-size':
// 这里检测下 tmp_path 是否存在
if (($tmp_path)) {
// 返回 JSON 格式的响应
return json(['size' => ($tmp_path)]);
}
break;
default:
# code...
break;
}js
// 咋触发这个函数我就不举例了
function downloadFile() {
var file_size = 0;
var progress = 0;
console.log("Prepared to download");
$.ajax({
url: './download.php?action=prepare-download',
type: 'GET',
dataType: 'json',
beforeSend: function() {
$('#update-button').html('<i class="fa fa-spinner fa-spin"></i> 正在准备').prop('disabled', 'disabled');
},
})
.done(function(json) {
console.log(json);
file_size = json.file_size;
$('#file-size').html(file_size);
// 显示进度条
console.log("started downloading");
$.ajax({
url: './download.php?action=start-download',
type: 'POST',
dataType: 'json'
})
.done(function(json) {
// set progress to 100 when got the response
progress = 100;
console.log("Downloading finished");
console.log(json);
})
.fail(showAjaxError);
var interval_id = window.setInterval(function() {
$('#imported-progress').html(progress);
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
if (progress == 100) {
clearInterval(interval_id);
// 到此远程文件下载完成,继续其他逻辑
} else {
$.ajax({
url: './download.php?action=get-file-size',
type: 'GET'
})
.done(function(json) {
progress = (json.size / file_size * 100).toFixed(2);
updateProgress(progress);
console.log("Progress: "+progress);
})
.fail(showAjaxError);
}
}, 300);
})
.fail(showAjaxError);
}
本文链接:http://so.lmcjl.com/news/198/