我已经在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";
Run Code Online (Sandbox Code Playgroud)
注意:我在内容分解中使用了.pdf扩展名.但这对我来说并不富有成效.还使用了readfile()函数,这对我也没有帮助.谁能告诉我那里有什么问题?
主要原因page is changing into gray colors是浏览器无法正确检测内容类型.
试试这个:
header("Content-type: $mimetype");
header('Content-Disposition: inline; filename="'.$question.'"'); // Filename should be there, not the content
Run Code Online (Sandbox Code Playgroud)
代替 :
header('Content-type: $mimetype');
header('Content-Disposition: inline; filename="$question"');
Run Code Online (Sandbox Code Playgroud)
您似乎有无效引号,因此未正确指定内容类型.
编辑
要清除,我们假设这$question是二进制PDF内容.
这就是你的代码应该是:
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename=anything.pdf');
header('Content-Transfer-Encoding: binary');
echo $question;
Run Code Online (Sandbox Code Playgroud)
错误解释
我们来讨论您的原始代码和错误.
$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";
Run Code Online (Sandbox Code Playgroud)
一个编辑
我有另一个查询...我想将文件名更改为$ year.pdf .. $ year可能有像2007这样的值.我可以这样做吗???
试试这个 :
$year = '2013'; // Assign value
header('Content-Disposition: inline; filename='.$year.'.pdf');
Run Code Online (Sandbox Code Playgroud)
代替:
header('Content-Disposition: inline; filename=anything.pdf');
Run Code Online (Sandbox Code Playgroud)