【问题标题】:View file stored in database using php on browser在浏览器上使用 php 查看存储在数据库中的文件
【发布时间】:2013-12-13 18:04:39
【问题描述】:

我正在尝试在浏览器上查看存储在数据库中的文件(即:excel 表格/pdf/图像)。

我已经编写了一个从数据库下载文件的代码,它正在运行,但我想在浏览器中显示它。

代码如下:

<?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 被下载,但没有查看任何内容。

有什么建议吗?

【问题讨论】:

  • PHP 在您的网络服务器上配置不正确,或者没有安装。
  • 我所有其他的 php 页面都可以工作!我下载了自动安装 php、sql 和 apache 的 wamp 服务器

标签: php mysql sql browser view


【解决方案1】:

根据您的代码,$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;

【讨论】:

  • 谢谢.. 它现在不下载,它会打开一个新页面。但是,出现错误并出现很多奇怪的字符
  • 那是因为代码的解释方式有问题,您正在显示二进制文件内容。在链接的手册页上阅读更多信息,以获取特定案例所需的所有标题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2018-10-04
  • 2012-03-30
  • 1970-01-01
  • 2020-07-25
  • 2014-03-13
  • 2012-04-10
相关资源
最近更新 更多