使用 cakephp 3 上传文件并将其存储在 blob 中

Upload files using cakephp 3 and store it in a blob

我知道在数据库中存储文件有点脏,但我需要上传文件并将其存储到数据库 BLOB 中,但我没有找到任何相关文档,也没有找到任何线索,因此我们将不胜感激。

提前致谢, 大卫

您不需要做任何特别的事情,只需将要存储的数据设置为适当的实体 属性(分别为数组键),可以是字符串,也可以是流.

BLOB 列将自动与 \Cake\Database\Type\BinaryType database type 关联,其中处理 storing/reading 二进制数据所需的所有内容。

这是一个抽象示例,展示了可能的用例

$data = [
    'file_a' => file_get_contents('path/to/file.ext'),
    'file_b' => fopen('path/to/file.ext', 'r'),
    'file_c' => 'foo bar baz'
];
$entity = $Table->newEntity($data);
$Table->save($entity);

读取的实体将始终以流的形式保存数据,因此您可以将它们与 Filesystem and Stream 函数一起使用,例如

$handle = $Table->get(1)->file_a;
while (!feof($handle)) {
    echo fread($handle, 8192);
}
echo stream_get_contents($Table->get(1)->file_a);