Upload files using cakephp 3 and store it in a blob

跟風遠走 提交于 2019-12-07 13:58:11

问题


I know that storing files in database is a little dirty, but I'm need to upload and store a file into a database BLOB and I haven't found any documentation about it and I haven't find any clue, so any help about it will be appreciated.

Thanks in advance, David


回答1:


There is nothing special that you'd need to do, simply set the data that you want to store in the appropriate entity property (respectively array key), either as a string, or as a stream.

BLOB columns will automatically be associated with the \Cake\Database\Type\BinaryType database type, where everything that is necessary for storing/reading binary data is being handled.

Here's an abstract example, showing possible use cases

$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);

The read entities will always hold the data as streams, so you can use them with the Filesystem and Stream functions, like

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


来源:https://stackoverflow.com/questions/32275558/upload-files-using-cakephp-3-and-store-it-in-a-blob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!