使用cakephp 3上传文件并将其存储在blob中 [英] Upload files using cakephp 3 and store it in a blob

查看:106
本文介绍了使用cakephp 3上传文件并将其存储在blob中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在数据库中存储文件有点脏,但我需要上传和存储一个文件到数据库BLOB,我还没有找到任何文档,我没有找到任何线索,所以



提前感谢
David

解决方案

没有什么特别的,你需要做,只需设置你想要存储在适当的实体属性(分别是数组键),作为一个字符串或流的数据。 / p>

BLOB 列会自动与 \Cake\Database\Type\BinaryType

这是一个抽象的例子,显示了可能的数据库类型

用例

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

读取的实体将始终将数据保存为流,因此您可以使用 文件系统 功能,例如

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





  echo stream_get_contents($ table-> get(1) - > file_a); 


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

解决方案

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

这篇关于使用cakephp 3上传文件并将其存储在blob中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆