最近在阅读PHP文档,看到session模块时,发现可以通过seession获取文件上传进度,于是动手实践了以下。
文档地址如下,文档还是要仔细看,我就不搬了:https://www.php.net/manual/zh/session.upload-progress.php
下面是我的demo,环境配置
配置文件php.ini
session.upload_progress.enabled = On
session.upload_progress.cleanup = On
session.upload_progress.prefix = "upload_progress_"
session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
session.upload_progress.freq = "1%"
session.upload_progress.min_freq = "1"
配置文件nginx.conf
fastcgi_request_buffering off;#这个很重要
环境说明:
1、php8.1
2、nginx 1.17.10
表单文件 index.php,form的target属性主要是控制上传完成后是否跳转页面,这里不跳转所有设定为内嵌的iframe的id
<form action="upload.php" method="POST" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="test" />
<input type="file" name="file1" />
<input type="file" name="file2" />
<input type="submit" value="upload"/>
</form>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank" style="display:none;"></iframe>
<div>进度:<span id="progress"></span></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function getProgress(){
$.get('progress.php',{<?php echo ini_get("session.upload_progress.name"); ?>:"test"},function(res){
$('#progress').text(res);
if(res != 100)
setTimeout('getProgress()',100);
})
}
$('form').submit(function(){
setTimeout('getProgress()',100);
});
</script>
文件上传处理 upload.php
写的别叫简单
<?php
foreach ($_FILES as $file){
move_uploaded_file($file['tmp_name'], 'files/'.time());
}
进度获取 progress.php
<?php
session_start();
$i = ini_get('session.upload_progress.name');
$key = ini_get("session.upload_progress.prefix") . $_GET[$i];
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
}else{
echo 100;
}
|