无法使用视图按钮在chrome上上载pdf文档

时间:2016-05-19 17:39:39

标签: php mysql pdf

我正在尝试在浏览器中查看存储在数据库中的文件(即:excel sheet / pdf / images)。我已经编写了一个从数据库下载文件的代码,它正在运行,但我想在浏览器中显示它。

这是我的代码

<?php
if(isset($_GET['id'])) {

$id = intval($_GET['id']);

// Make sure the ID is in fact a valid ID
if($id <= 0) {
    die('The ID is invalid!');
}
else {
    // Connect to the database
    $con = new mysqli("localhost", "root", "", "crystalwnj");
    if(mysqli_connect_errno()) {
        die("MySQL connection failed: ". mysqli_connect_error());
    }

    // Fetch the file information
    $query = "
        SELECT `mime`, `name`, `size`, `data`
        FROM `file`
        WHERE `id` = {$id}";
    $result = $con->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


            $file=$row['data'];
            $filename=$row['name'];
            header("Cache-Control: maxage=1");
            header("Pragma: public");
            header("Content-Type: ". $row['mime']);
            header('Content-Disposition: inline; filename="'. $filename. '"');
            header("Content-Description: File Tranfer");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ". $row['size']);
            header("Accept-Ranges: bytes");

            // Print data
            readfile($row['name']);

        }
        else {
            echo 'Error! No image exists with that ID.';
        }

        // Free the mysqli resources
        @mysqli_free_result($result);
    }
    else {
        echo "Error! Query failed: <pre>{$con->error}</pre>";
    }
    @mysqli_close($con);
}

0 个答案:

没有答案