【问题标题】:not supported or damaged pdf/doc file when downloading in php在 php 中下载时不支持或损坏 pdf/doc 文件
【发布时间】:2013-03-28 14:19:11
【问题描述】:

我正在使用 php 下载 PDF/DOC 文件

这是我的 html 代码:

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

这是我在 pdf_server.php 文件中的 php 代码

<?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 是我的 test.pdf 文件所在的文件夹。当我单击链接下载文件时。浏览器显示要下载的文件及其大小(1.4 mb),但是当下载完成并打开文件时,它显示文件损坏或文件不受支持的错误。然后我检查它的属性,它显示 0 字节。

请帮忙

【问题讨论】:

  • application/force-download 似乎不是标准的 mime 类型
  • 接受有效答案

标签: php download


【解决方案1】:

试试这个-

<?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();
}
?>

【讨论】:

  • 嘿,它现在可以工作了谢谢
  • 我尝试了很多解决方案,都给出了相同的错误,但是你的是最完整的,它可以工作,也可以在控制器内部使用。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2015-07-16
  • 2011-03-30
相关资源
最近更新 更多