首页 > 解决方案 > 无法将 PDF 文档加载到我的数据库 php 中的 blob 类型

问题描述

我有一个数据表单表单,我将 pdf 文件上传到 blob 类型字段,我的问题是当我想显示它时,它总是给我消息:加载 PDF 文档失败。是按照我的代码:

     $code = mysqli_real_escape_string($conn , $_GET['doc']); 
 $q = mysqli_query($conn, ' SELECT document FROM saisie WHERE code = "'.$doc.'" ');  
 $r= mysqli_fetch_assoc($q);  
 $doc=$r['document'];

 header('Content-Type: application/pdf') ; 
 header('Content-Disposition: inline; filename="test.pdf"') ;
 header('Content-Transfer-Encoding: binary');
 header('Accept-Ranges: bytes');
 @readfile($doc) ;

标签: phpmysqlpdf

解决方案


这是一个简单的脚本,对我来说很好用:

<?php

$db = new PDO("mysql:host=localhost;dbname=test", "test","");

// Read the file and store as blob into DB
$filename = 'doc.pdf';
$fileContents = file_get_contents($filename);

$stmt = $db->prepare("insert into pdf_blob(filename, data) values (?, ?)");
$stmt->execute([$filename, $fileContents]);


// Read blob data from DB and output in browser
$stmt = $db->prepare("select filename, data from pdf_blob where filename = ? limit 1");
$stmt->execute([$filename]);
$result = $stmt->fetch();

header('Content-Type: application/pdf') ;
header('Content-Disposition: inline; filename="test.pdf"') ;
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

echo $result['data'];

我使用file_get_contents()从文件系统读取 PDF 文件,并将内容存储到 MySQL BLOB 列中。之后,我从数据库中读取相同的数据并简单地echo用于输出。标头声明与您的代码中的完全相同。

虽然我在这里使用PDO而不是mysqli,但这可能无关紧要。

这是我的表定义:

CREATE TABLE `pdf_blob` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `filename` VARCHAR(50) NOT NULL,
    `data` BLOB NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB;

推荐阅读