我目前正在用 PHP 开发一个应用程序,其中我的服务器(专用服务器)必须下载文件,并且用户应该同时下载该文件。
这是一个例子:
- 服务器开始一次下载一个文件A。
- 用户想要在时间 A + 3 秒(例如)时下载此文件
我已经解决了这个问题:“如果用户下载文件的速度比服务器快..”。但我不知道如何制作一个用户要下载完整文件的php脚本(这意味着大小必须是文件的完整大小,而不是A + 3秒时当前下载的大小)。我已经做到了:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$data['name'].'";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$data['size']);
readfile($remoteFile);
但它不起作用,用户将仅下载服务器上当前的大小(这会损坏文件),而不是完整的文件...
如果您有任何解决方案,谢谢。
最佳答案
您可以通过打开连接并读取来手动传输文件,直到读完所有 header 为止。然后,一旦您计算出 Content-Length
,将其发送给用户并回显
您获得的所有剩余数据(请使用 flush()
并避免输出缓冲区)。
伪代码(-ish):
open the file
# grab headers
while you didn't get all HTTP headers:
read more
look for the Content-Length header
send the Content-Length header
# grab the file
while the rest of the request isn't done
read more
send it to the user
flush the buffers
done
关于php - 同时在服务器和用户上下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8466422/