简体   繁体   English

如何使用PHP检索/下载MySQL数据库中BLOB中存储的文件

[英]How to retrieve/download a file stored in a BLOB in a MySQL DB using PHP

The other day I recently wrote a program that takes a file that a user provided and inserts the actual file(driver) into a MySQL database BLOB. 前几天,我最近写了一个程序,该程序接收用户提供的文件,并将实际文件(驱动程序)插入到MySQL数据库BLOB中。 I did the insertion as follows: 我做了如下插入:

$sql = "INSERT INTO Drivers (driver, filename, status, version, environments) VALUES(LOAD_FILE('$driver'), '$filename', $statusid, $driver_version, '$environments')";

As you can see above, the 'driver' field is the BLOB. 如您在上面看到的,“驱动程序”字段是BLOB。 I have the filename as well in a different field. 我在另一个字段中也有文件名。 So the question is, how can I easily get the BLOB and put it back into an actual file? 因此,问题是,如何轻松获得BLOB并将其放回实际文件中? I need to get this into a file so that I can upload it to a server via SCP. 我需要将其保存到文件中,以便可以通过SCP将其上传到服务器。 I've seen a few examples out there with content headers and such and they all look too complicated. 我已经看到了一些带有内容标头的示例,它们看起来都太复杂了。 It was easy to load with LOAD_FILE() and I didn't know if there was another simple option to get it back to an actual file? 使用LOAD_FILE()加载很容易,我不知道是否还有另一个简单的选项可以将其恢复为实际文件? Sorry I don't have any code examples. 抱歉,我没有任何代码示例。 I really don't know where to start. 我真的不知道从哪里开始。

Your sql table should have at least two extra fields: 您的sql表应该至少有两个额外的字段:

`mime_type` varchar(255) NOT NULL,
`size` int(10) unsigned NOT NULL,

where: 哪里:

  • mime_type is mime_content_type($path) and mime_type是mime_content_type($path)
  • size is the file's size in bytes, filesize($path) size是文件的大小,以字节为单位, filesize($path)

and PHP code should look like: 和PHP代码应如下所示:

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: {$file['mime_type']}");
header("Content-Transfer-Encoding: binary");
header("Content-Length: {$file['size']}");
header("Content-disposition: inline; filename= {$file['filename']}");

return $file['driver'];

The reasons for storing data as binary in SQL are dictated by business rules. 在SQL中以二进制形式存储数据的原因由业务规则规定。 For example, I store contracts that have to remain private. 例如,我存储必须保密的合同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM