PHP下载脚本错误加载PDF文档失败

我有一个简单的下载脚本,可以在下面找到:


if (isset($_GET['name'])){


        $name = $_GET['name'];


        $stmt = $conn->prepare("SELECT link_to_policy FROM policies WHERE name = ? LIMIT 1");

        $stmt->bind_param('s', $name);

        $stmt->execute();

        $result = $stmt->get_result();

        $result2 = $result->fetch_assoc();


        $policytodownload = $result2["link_to_policy"];

        if (file_exists($policytodownload)) {

            header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");

            header("Content-Type: application/msword");

            header("Content-Type: application/pdf");

            header('Content-Disposition: attachment');

            header("Cache-Control: no-cache");

            header('Content-Length: ' . filesize($policytodownload));

            ob_clean();

            flush();

            readfile($policytodownload);

            exit;

        }   

    }   

link_to_policy 列包含保存策略的文件的完整路径。点击链接后,文件被下载,但点击文件后,即使是word文档,我在Chrome中收到错误信息(所有PDF文件都是在那里打开的):Failed to load PDF文档。


你能帮我么?谢谢!


米琪卡哇伊
浏览 247回答 1
1回答

慕尼黑8549860

不要发送多个Content-type标头,发送文件扩展名的适当类型。if (isset($_GET['name'])){    $name = $_GET['name'];    $stmt = $conn->prepare("SELECT link_to_policy FROM policies WHERE name = ? LIMIT 1");    $stmt->bind_param('s', $name);    $stmt->execute();    $result = $stmt->get_result();    $result2 = $result->fetch_assoc();    $policytodownload = $result2["link_to_policy"];    if (file_exists($policytodownload)) {        $type_map = ['xls' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',                     'doc' => 'application/msword',                     'pdf' => 'application/pdf'];        $ext = pathinfo($policytodownload, PATHINFO_EXTENSION);        if (isset($type_map[$ext])) {            header("Content-Type: {$type_map[$ext]}");        }        header("Cache-Control: no-cache");        header('Content-Length: ' . filesize($policytodownload));        ob_clean();        flush();        readfile($policytodownload);        exit;    }   }
打开App,查看更多内容
随时随地看视频慕课网APP