【发布时间】:2015-02-03 18:05:02
【问题描述】:
我创建了一个搜索表单,用户可以在其中输入图像代码,搜索时它会让用户下载文件。下面是我的代码
<html>
<head>
<title>Search Contacts</title>
</head>
<body>
<h3>Search Client File</h3>
<form method="post" action="#" id="searchform">
Type the File Code:<br><br>
<input type="text" name="fcode">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$filecode=$_POST["fcode"];
if (!empty($filecode))
{
$file="/var/www/website/$filecode.pdf";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
}
else
{
echo "No Results";
}
?>
</body>
</html>
问题是下载的文件无法查看,或者无法查看,我的代码似乎有什么问题?
【问题讨论】:
-
文件顶部的标记是否也被渲染到输出?如果是这样,没有 PDF 阅读器会理解它。通常响应文件会在 PHP 脚本中单独发生,而不是被额外的标记包围。
-
@David 对不起,“标记”是什么意思
-
“标记”是“HTML”中的“M”。我的意思是,如果响应同时包含 HTML 和 PDF 文件,那么它不是有效的 PDF。
-
@David 你能建议我应该如何纠正这个问题吗?
-
嗯,首先你要确认这是否真的是错误。这可以通过检查响应在浏览器的调试工具中确认。如果响应包含此页面中的 HTML,那就是问题所在。 (可能还有其他问题,但要诊断它们,您需要纠正这个问题。)我不完全确定这是问题所在,因为它应该在内容已经开始。