使用php查看存储在数据库中的pdf到浏览器中

时间:2012-03-14 00:51:19

标签: php mysql pdf web-applications

嘿我想创建一个按钮,将存储在mysql数据库中的pdf文件查看到浏览器中,所以我的代码如下:

那是一个.php文件,显示数据库中所有pdf文件的列表,带有2个按钮下载/查看

$sql = 'SELECT `id`, `name`, `type`, `size`, `created` FROM `file`';
$result = $dbLink->query($sql);

// Check if it was successfull
if($result) {
    // Make sure there are some files in there
    if($result->num_rows == 0) {
        echo '<p>There are no files in the database</p>';
    }
    else {
        // Print the top of a table
        echo '<table width="100%">
                <tr>
                    <td><b>Name</b></td>
                    <td><b>type</b></td>
                    <td><b>Size (bytes)</b></td>
                    <td><b>Created</b></td>
                    <td><b>&nbsp;</b></td>

                </tr>';

        // Print each file
        while($row = $result->fetch_assoc()) {

            echo "
                <tr>
                    <td>{$row['name']}</td>
                    <td>{$row['type']}</td>
                    <td>{$row['size']}</td>
                    <td>{$row['created']}</td>
                    <td><a href='get_file.php?id={$row['id']}'>Download</a></td>
                    <td><a href='view.php?id={$row['id']}'>View</a></td>

                    </tr>"; 
        }

        // Close table
        echo '</table>';
    }

    // Free the result
    $result->free();

}
else
{
    echo 'Error! SQL query failed:';
    echo "<pre>{$dbLink->error}</pre>";
}

// Close the mysql connection
$dbLink->close();
?>

这是由View按钮触发的view.php:

<?php
        $id = intval($_GET['id']);
$file = "
            SELECT `type`, `name`, `size`, `data`
            FROM `file`
            WHERE `id` = {$id}";

header('Content-type: application/pdf');
header('Content-Disposition: inline');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
header("Location: $file");
@readfile($file);
?>

每当我点击查看按钮时出现错误"file does not start with %PDF-" although i am sure that the files in the database are of type pdf. so anyone can solve this problem?

的问题

0 个答案:

没有答案