php 实时获取已下载文件大小

使用php 如何获取已下载文件的大小
想做个实时下载进度 我想把已下载的文件大小返回给前端

阅读 3.1k
4 个回答
<?php
$fp = fopen("http://zhangmenshiting.qianqian.com/data2/music/3423b48bd35de901b3512fc1f28cd2e3/567299874/56729985416560064.mp3?xcode=1910cd6f28d29cd260e85653b43f0cf4", "rb");
$dfp = fopen("a.mp3", "wb");
$downloaded = 0;
while (!feof($fp)) {
    $line = fread($fp, 4096);
    $size = strlen($line);
    $downloaded += $size;
    fwrite($dfp, $line, $size);
    printf("%.2fMB\r", $downloaded / 1024 / 1024);
}
fclose($fp);
fclose($dfp);
printf("\n");

函数 filesize() ?还是说配置请求头部 Content-Length ?

$dst_file = fopen(sys_get_temp_dir() . '/' . uniqid($time) . '.txt','w');     
     
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 20971520);
$flag=0;
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch ,$str) use (&$flag,$dst_file){
    $len = strlen($str);

    file_put_contents($dst_file,$str,FILE_APPEND);
    return $len;
});

$output = curl_exec($ch);
fclose($dst_file);
curl_close($ch);

curl下载文件可以用上面的方法。

……没懂,前端想拿下载进度的话可以用Ajax啊?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题