dousi2553 2013-03-28 05:57 采纳率: 0%
浏览 122
已采纳

在php下载时不支持或损坏pdf / doc文件

I am downloading PDF/DOC files using php

This is my html code :

<a title="Download" target="_new" href="includes/pdf_server.php?file=test.pdf">Test PDF</a>

This is my php code in pdf_server.php file

<?php
$file = $_GET["file"];
if (file_exists("../PDF/".$file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
    // header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize("../PDF/".$file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

PDF is the folder where I have my test.pdf file . When I click on link to download file. Browser shows file to download with its size (1.4 mb) but when download finished and I open the file it shows error either file damaged or not supported file. Then I check it's properties it shows 0 bytes.

Please help

  • 写回答

1条回答 默认 最新

  • duanqiang5722 2013-03-28 06:10
    关注

    Try this-

    <?php
    $file_name = $_GET["file"];
    if (file_exists("../PDF/".$file_name)) {
        header('Pragma: public');   // required
        header('Expires: 0');       // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ("../PDF/".$file_name)).' GMT');
        header('Cache-Control: private',false);
        header('Content-Type: '.'application/pdf');
        header('Content-Disposition: attachment; filename="'.basename("../PDF/".$file_name).'"');
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: '.filesize($file_name));    // provide file size
        header('Connection: close');
        readfile("../PDF/".$file_name);     // push it out
        exit();
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行