【问题标题】:Displaying pdf file stored in the server and downloading it using php显示存储在服务器中的pdf文件并使用php下载
【发布时间】:2012-09-18 06:57:20
【问题描述】:

我已将 .pdf、.doc、.txt 文件存储在 Web 服务器的目录中。我能够显示存储在目录中的所有文件,但下载失败。每次我点击超链接 sample.txt 都会下载空白内容。请查看代码并建议我。

这就是我在 show_directory.php 中使用的内容

<?PHP
    // Define the full path to your folder from root 
    $path = "/public_html/bc/upload/"; 

    // Open the folder 
    $dir_handle = @opendir($path) or die("Unable to open $path"); 

    // Loop through the files 
    while ($file = readdir($dir_handle)) { 

    if($file == "." || $file == ".." || $file == "download_file.php" ) 

        continue; 
        echo "<a href=\"download_file.php\">$file</a><br />"; 


    } 
    // Close 
    closedir($dir_handle); 
?>

download_file.php的内容是:

<?PHP
//download.php
//content type
header('Content-type: text/plain');
//open/save dialog box
header('Content-Disposition: attachment; filename="sample.txt"');
//read from server and write to buffer
readfile('test.txt');
?>

【问题讨论】:

    标签: php file filesystems download


    【解决方案1】:
    ....
    header('Content-Description: File Transfer');
    header('Content-type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . 'test.txt' . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    readfile('test.txt');
    ....
    

    为什么不使用二进制?

    【讨论】:

    • 这没有帮助,看我有 2 个名为 abc.doc 和 xyz.pdf 的文件保存在 $path = "/public_html/bc/upload/" 中,我正在使用循环显示两个文件都回显 "$file
      ";显示部分工作正常,但我无法下载文件。按照您在代码中的建议使用二进制文件后,当我单击它时,会下载一个名为 test.txt 的空白文本文件。
    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2014-10-15
    • 2013-08-25
    • 1970-01-01
    • 2016-08-06
    • 2014-11-14
    相关资源
    最近更新 更多