强制下载只显示在浏览器中,没有下载提示


Force Download Only Displays in Browser, Doesn't Prompt for Download

我似乎弄不明白,我知道这很简单。我正在构建一个非常基本的内容管理系统的后端。对于这个特定的部分,我只是试图创建一个PHP链接,允许一个文件(客户的简历)被下载。

我的问题:

当点击下载文件的链接时,浏览器不会提示您选择一个本地目录来保存文件,而是简单地显示文件和文档内容前后的一堆符号(我假设这是文件的打开和关闭exif数据,供应用程序破译)。

我怎样才能强制浏览器提示用户"另存为…"?

<?php
require("connect.php");
$query = "SELECT * FROM kb_info LIMIT 1";
$result = mysql_query($query, $link);
while ($row = mysql_fetch_array($result)) {
    $file_extension = end(explode(".", $row["extension"]));
    if ($file_extension == doc) {
        header('Content-disposition: attachment; filename='.$row["extension"]);
        header('Content-type: application/doc');
        header ("Content-Length: ".filesize($row["extension"]));
        readfile($row["extension"]);
        exit;
    }
    if ($file_extension == docx) {
        header('Content-disposition: attachment; filename='.$row["extension"]);
        header('Content-type: application/docx');
        header ("Content-Length: ".filesize($row["extension"]));
        readfile($row["extension"]);
        exit;
    }
    if ($file_extension == pdf) {
        header('Content-disposition: attachment; filename='.$row["extension"]);
        header('Content-type: application/pdf');
        header ("Content-Length: ".filesize($row["extension"]));
        readfile($row["extension"]);
        exit;
    }
}    
?>  
许多谢谢,

Joshie

我认为问题可能是在PHP文件的某个地方有一些空白,这导致头不能正确发送,因此您看到整个输出。

我建议以下步骤:

  1. 检查"connect.php"并在文件的开头/结尾查找空行/空格并删除它们

  2. 以这种方式调整php文件,在文件末尾省略结束标记?> -这样您就不会在文件末尾得到空行

  3. 如果以上还不够,你需要检查你的apache和php的错误日志和/或设置错误日志,所以你也会看到警告-你会被告知,如果头没有正确发送或如果有一些其他错误

我用来下载的标头:

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-type: application/force-download");
        header("Content-Disposition: attachment; filename=".$file); 
        header("Content-Type: application/octet-stream");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".$bytes."");