【发布时间】:2020-06-18 03:29:56
【问题描述】:
我编写了一些 PHP 代码,可以从服务器上的 MySQL 数据库下载 PDF 文件。该代码运行良好,我可以从各种浏览器查看/下载/打开 PDF 文件。但是,当我下载文件并尝试通过 Adobe Reader 打开时,我收到一条消息,指出文件无法打开,因为“因为它不是受支持的文件类型或文件已损坏(例如,它已作为电子邮件附件发送且未正确解码)”
我确信我忘记在我的代码中做一些愚蠢的事情。以下是我正在使用的 PHP 代码:
// Downloads files
if (isset($_GET['scenario_id'])) {
$scenario_id = $_GET['scenario_id'];
// fetch file to download from database
$sql = "SELECT * FROM market_plans_pdfs WHERE scenario_id=$scenario_id";
$result = mysqli_query($connect, $sql);
$file = mysqli_fetch_assoc($result);
$pdf_file=$file['pdf_file'];
$filename=$file['scenario_name'];
if (isset($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="'.basename($filename).'"');//set content-disposition as "inline" as opposed to "attachment" so that it opens first in the browser
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
@readfile("data:application/pdf;base64,$pdf_file");
}
}
任何帮助都将不胜感激,因为我在网上尝试了各种解决方案,但均未成功。
【问题讨论】:
-
@readfile("data:application/pdf;base64,$pdf_file");它不是一个文件,所以readfile是错误的,而只是回显数据,例如:echo $pdf_file;,如果它们是 base64 编码,则在之前解码它们 -
@Kazz。感谢您及时的回复。我已经用
echo $pdf_file删除了@readfile 行,并在回显之前添加了$pdf_file=base64_decode($pdf_file)。这也像以前一样工作。我可以下载/查看文件,但是当我尝试通过 Adobe Reader 打开时,我收到了关于无法打开文件的相同消息。 -
你能上传你在adobe reader中无法读取的文件吗?
-
@Kazz.. 这是 Dropbox 文件夹 (dropbox.com/s/utejtwcydvlieg7/test_upload.pdf?dl=0) 中文件的链接。另外,当我上传 pdf 文件时,我使用了
$pdf = base64_encode(file_get_contents(addslashes($pdf))); -
哦,我现在明白了,您不要将其他输出与文件本身分开,确保前后没有输出,该文件中包含整个网站