PHP-无法从数据库下载.pdf文件,文件内容存储在mysql数据库中

时间:2013-03-14 14:36:51

标签: php mysql pdf

我在php中写了一个代码,它将回显一个pdf文件。每当我试图回显那个pdf时,浏览器页面就会变成灰色,左下角的加载图标出现了,之后就出现了未能显示该pdf文件。

我可以向你保证,从数据库获取数据的代码是完美的。没有错误或错误。在获取数据后我使用了以下标题来回显该文件。我不确定这些标题。

$mimetype = 'application/pdf';
$disposition = 'attachment';
header('Content-type: $mimetype');
header('Content-Disposition: inline; filename="$question"');
header('Content-Transfer-Encoding: binary');
header('Content-length: ' . strlen($question));
header('Accept-Ranges: bytes');
echo "$question";

注意:我在内容分解中使用了.pdf扩展名。但这对我来说并不富有成效。还使用了readfile()函数,对我来说也没用。谁能告诉我那里有什么问题?

1 个答案:

答案 0 :(得分:6)

page is changing into gray colors的主要原因是浏览器无法正确检测内容类型。

试试这个:

header("Content-type: $mimetype");
header('Content-Disposition: inline; filename="'.$question.'"'); // Filename should be there, not the content

而不是:

header('Content-type: $mimetype');
header('Content-Disposition: inline; filename="$question"');

似乎您的引号无效,因此未正确指定内容类型。

修改

要清除,我们假设$question是二进制PDF内容 这就是你的代码应该是:

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename=anything.pdf');
header('Content-Transfer-Encoding: binary');
echo $question;

错误解释

让我们讨论您的原始代码和错误。

$mimetype = 'application/pdf';
$disposition = 'attachment';

// First error: you have single quotes here. So output is 'Content-type: $mimetype' instead of the 'Content-type: application/pdf'
header('Content-type: $mimetype');

// Second error. Quotes again. Additionally, $question is CONTENT of your PDF, why is it here?
header('Content-Disposition: inline; filename="$question"');


header('Content-Transfer-Encoding: binary');

// Also bad: strlen() for binary content? What for?
header('Content-length: ' . strlen($question));


header('Accept-Ranges: bytes');
echo "$question";

ONE MORE EDIT

  

我有另一个查询...我想将文件名更改为$ year.pdf .. $   年份可能有像2007年的价值。我可以这样做吗???

试试这个:

$year = '2013'; // Assign value
header('Content-Disposition: inline; filename='.$year.'.pdf');

而不是:

header('Content-Disposition: inline; filename=anything.pdf');