【发布时间】:2017-04-04 00:22:52
【问题描述】:
我是 PHP 新手,正在尝试通过代码实现以下功能
功能: 我有一个下载按钮,点击后我应该能够下载存储在 htdocs-->xxfilename-->abc.pdf 下的 .pdf 文件;
代码: 我在我的 xyz.php 网页中使用以下代码
<?php
$title = "Learning";
$content = '
<h3> Intro</h3>
<p>
Introduction goes here
</p>
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download" name="dwnld_file"/>
</form>
';
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("PQR");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = '$row["col2"]';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $row["col2"] . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile($file);
}
}
include 'Template.php';
?>
错误: 我的 pdf 文件正在下载,但打开时显示“加载 pdf 文档失败”
请帮助我哪里错了。
***编辑**** 我尝试了不同的方法,我的文件正在下载,但仍然显示“无法加载 pdf 文档”
我的其他方法代码如下
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download " name="dwnld_file"/>
</form>
<?php
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = $row["col1"];
echo $file;
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' .$file. '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile('myfile/'.$file);
}
}
?>
如果我做错了什么,请告诉我。
【问题讨论】:
-
这是一种非常丑陋的实现方式。
-
看起来这里有类似问题的可接受答案stackoverflow.com/questions/1004478/read-pdf-files-with-php
-
@Amit:你能提出更好的方法吗?请注意,我的所有页面都有通用模板。在其中一个页面中,我需要显示下载 PDF 按钮来下载 PDF 文件。