php - 无法将 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) ;
解决方案
这是一个简单的脚本,对我来说很好用:
<?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;
推荐阅读
- javascript - ReactJs如何呈现关联数组的对值
- node.js - MongoNetworkError:第一次连接时无法连接到服务器 [localhost:27017] [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
- spring-boot - 如何在 Spring Boot 2.0 上将默认 hikari cp 替换为 tomcat 池
- javascript - Angular2 文本掩码添加对文本的支持
- linux - 将修改日期更改为文件名
- apache - Apache htaccess 缓存
- amazon-s3 - 日期为“通配符参数”的 aws cp 文件
- azure - Azure AD B2C 'newUser' 和 'auth_time' 声明生命周期
- php - 无法在 wamp64 中使用 mail() 或 phpmailer 通过 php 发送邮件
- javascript - 在流星 js 中显示来自 mongodb 的 Summernote 内容时出错