简体   繁体   English

如何使文件可下载

[英]How to make a file downloadable

Am trying to add file download to my site for audio video and pdf files Am using the php header() function but instead of downloading the output file, it keeps on downloading the php page instead. 我试图使用php header()函数将文件下载添加到我的网站上以获取音频视频和pdf文件,但是我没有继续下载输出文件,而是继续下载php页面。 here is my code. 这是我的代码。

    header('Content-disposition: attachment; 
            Content-type: audio/mpeg; 
            filename=thefile.type');

You need to write the contents of the file out, eg 您需要写出文件内容,例如

header('Content-disposition: attachment; 
   Content-type: audio/mpeg; 
   filename=thefile.type');
echo file_get_contents("thefile.type");

This works pretty well 这个效果很好

    if (file_exists("audio/thefile.type"))
    {
         if (FALSE!== ($handler = fopen('thefile.type', 'r')))
            {
             header('Content-Description: File Transfer');
             header('Content-Type: application/octet-stream');
             header('Content-Disposition: attachment; 
                     filename=audio/thefile.type');
             header('Content-Transfer-Encoding: chunked'); //changed to chunked
             header('Expires: 0');
             header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
             header('Pragma: public');
             //header('Content-Length: ' . filesize('thefile.type')); //Remove

             //Send the content in chunks
             while(false !== ($chunk = fread($handler,4096)))
                  {
                    echo $chunk;
                  }
             }
             exit;
    }
    else{

           echo "<h1>Content error</h1><p>The file does not exist!</p>";
         }

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

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