dsiuz86842 2019-07-30 20:14
浏览 263
已采纳

PHP下载脚本错误无法加载PDF文档

I have a simple download script that can be found below:

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 column contains the full path to the file where the policy has been saved. After clicking on the link, the file is downloaded, but after clicking on the file, even if it is a word document, I receive an error message in Chrome (all the PDF files are meant to be opened there): Failed to load PDF document.

Can you please help me? Thank you!

  • 写回答

1条回答 默认 最新

  • dora1989 2019-07-30 21:34
    关注

    Don't send multiple Content-type headers, send the appropriate type for the file extension.

    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;
        }   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题