从mysql数据库中读取pdf文件

时间:2016-04-01 10:53:37

标签: php mysql

我正在使用此示例http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

上传部分没有任何问题。但是我在下载部分面临很多问题。我想创建一个用户点击的链接,然后他就可以下载相应的pdf。但页面运行并且锚标记可见。但是当我点击它时.htm文件正在下载 下面是我的download.php



<html>
<head>
<title>Download File From MySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?php
include 'config.php';
include 'opendb.php';

$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty <br>";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>
<?php echo "<a href='download.php?id='".$id.";>Download</a> <br>";

}
}
include 'closedb.php';
?>
</body>
</html>
<?php
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database

include 'config.php';
include 'opendb.php';

$id    = $_GET['id'];
$query = "SELECT name, type, size, content " .
         "FROM upload WHERE id = '$id'";

$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);

header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;

include 'closedb.php';
exit;
}

?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

问题在于,无论用户是想查看要下载的文件,还是想下载文件本身,都会在页面顶部启动html输出。在那一刻,要下载的文件会出现一个html页面。

您的代码应该首先检查是否设置了id参数。如果没有,那么你开始生成html页面。如果是,那么您从数据库中读取文件,设置标题并将内容发回。

或者只是使用不同的php页面来显示文件列表并下载其中一个文件。

相关问题