简体   繁体   English

使用PHP下载大文件

[英]Download large files with PHP

I'm using jQuery with PHP. 我在PHP上使用jQuery。 I've written a simple download function with PHP: 我用PHP编写了一个简单的下载功能:

function downloadFile($sFile){
        #Main function
        header('Content-Type: '.mime_content_type($sFile)); 
        header('Content-Description: File Transfer');
        header('Content-Length: ' . filesize($sFile)); 
        header('Content-Disposition: attachment; filename="' . basename($sFile) . '"');
        readfile($sFile);
    }

I can download a file through this script, but if it's a large files(like 1GB), the readfile function needs his time until the download start. 我可以通过此脚本下载文件,但是如果文件很大(例如1GB),则readfile函数需要他的时间才能开始下载。 So i have to wait about a minute or something, until the download really starts. 因此,我必须等待一分钟左右,直到真正开始下载为止。 Any idea how to optimze my script, so the download starts immediately? 知道如何优化我的脚本,以便立即开始下载吗?

You could configure Apache to set the proper headers in your .htaccess file. 您可以配置Apache以在.htaccess文件中设置适当的标头。 Then, you could link directly to the file instead of the PHP page. 然后,您可以直接链接到文件而不是PHP页面。 This will also reduce server load. 这还将减少服务器负载。

Of course, if the PHP script performs functions other than just setting headers (such as authentication) then this is not an option. 当然,如果PHP脚本执行的功能不仅仅是设置标头(例如身份验证),那么这不是一个选择。 You will have to pass the file through PHP in chunks as @NB mentions in his comment. 正如@NB在他的评论中提到的那样,您将必须通过PHP将文件分块传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM