显示存储在MySQL数据库PHP中的PDF文件

时间:2012-03-14 20:41:11

标签: php mysql web-applications adobe-reader

我试图在用户请求时在浏览器中显示存储在mysql数据库中的PDF文件。

MySQL表的结构:

CREATE TABLE `file` (
`id` Int Unsigned Not Null Auto_Increment,
`name` VarChar(255) Not Null Default 'Untitled.txt',
`mime` VarChar(50) Not Null Default 'text/plain',
`size` BigInt Unsigned Not Null Default 0,
`data` MediumBlob Not Null,
`created` DateTime Not Null,
PRIMARY KEY (`id`)
)

php代码:

$query = "
            SELECT `type`, `name`, `size`, `data`, `mime`
            FROM `file`
            WHERE `id` = {$id}";
        $result = $dbLink->query($query);
        if($result) {
            // Make sure the result is valid
            if($result->num_rows == 1) {
            // Get the row
                $row = mysqli_fetch_assoc($result);
                // Print headers
                header('Accept-Ranges: bytes');
                header('Content-Transfer-Encoding: binary');
                header("Content-Type: ".$row['mime']);
                header("Content-Length: ".$row['size']);
                header("Content-Disposition: inline; filename=".$row['name']);
                echo $row['data'];
            }
        }

将文件保存到数据库的代码:

if(isset($_FILES['uploaded_file'])) {
    // Make sure the file was sent without errors
    if($_FILES['uploaded_file']['error'] == 0) {
        // Connect to the database
        $dbLink = new mysqli('localhost', 'REDACTED',"REDACTED", 'pdfs');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ".mysqli_connect_error());
        }

        // get all required data
        $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
        $type = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
        $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['name']));
        $size = intval($_FILES['uploaded_file']['size']);

        // Create the SQL query
        $query = "
            INSERT INTO `file` (
                `name`, `type`, `size`, `data`, `created`
            )
            VALUES (
                '{$name}', '{$type}', {$size}, '{$data}', NOW()
            )";

        // Execute the query
        $result = $dbLink->query($query);

        // Check if it was successfull
        if($result) {
            echo 'Success! Your file was successfully added!';
        }
        else {
            echo 'Error! Failed to insert the file'
               . "<pre>{$dbLink->error}</pre>";
        }

但是,当我尝试查看pdf时,adobe reader开始加载,然后我收到此错误消息:

  

文件已损坏且无法修复。   我做错了什么?

2 个答案:

答案 0 :(得分:1)

坦率地说,我根本不喜欢这种方式。

KISS

保持简短&amp;简单

无论你想做什么,都有更好的方法。

  1. 如果安全性问题,您有.htaccess和访问角色
  2. 如果文件处理是问题,那么你有PHP。
  3. 如果受保护的下载是一个问题,那么再次结合使用PHP及其会话处理,就可以做到。
  4. 如果查看问题,您可以使用浏览器。
  5. 如果你想强行下载文件,那么PHP的header标签就足够了。

答案 1 :(得分:0)

调用die();在echo $ row ['data']之后;确保数据后没有添加其他输出。不确定这是否是问题,但它将消除它作为一种可能性。