我正在尝试在浏览器中查看存储在数据库中的文件(例如:excel sheets / pdf / images)。
我已经编写了一个从数据库下载文件的代码,它正在运行,但我想在浏览器中显示它。
以下是代码:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
$id = $_GET['id']; // ID of entry you wish to view. To use this enter "view.php?id=x" where x is the entry you wish to view.
$query = "SELECT fileContent, filetype FROM file where id = $id"; //Find the file, pull the filecontents and the filetype
$result = MYSQL_QUERY($query); // run the query
if($row=mysql_fetch_row($result)) // pull the first row of the result into an array(there will only be one)
{
$data = $row[0]; // First bit is the data
$type = $row[1]; // second is the filename
Header( "Content-type: $type"); // Send the header of the approptiate file type, if it's' a image you want it to show as one :)
print $data; // Send the data.
}
else // the id was invalid
{
echo "invalid id";
}
?>
如果下载了view.php并且没有查看任何内容,那么会发生什么。
有什么建议吗?
答案 0 :(得分:0)
根据您的代码,$row[1]
是“文件名”。内容类型标题应包含内容类型,即文件mime类型,例如:
header('Content-type: application/pdf');
如果要添加文件名:
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename='.$row[1]);
print $data;
请确保$data
是文件的内容,例如您可以从readfile()获取该内容。
阅读手册的更多内容:http://php.net/manual/en/function.readfile.php
请记住,虽然浏览器可以轻松查看PDF和图像,但我认为Excel需要一些 ad hoc 插件。
一个更完整的示例,直接来自手册,以便您获得更全面的想法(并非所有这些标题都是必需的,您应该根据代码更改其他标题):
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));
ob_clean();
flush();
readfile($file);
exit;