简体   繁体   English

Yii2 将文件保存到 Oracle BLOB

[英]Yii2 saving file to Oracle BLOB

Problem is that i can't save file to blob.问题是我无法将文件保存到 blob。 It works without any error, temp file is created and i can read from it.它可以正常工作,没有任何错误,创建了临时文件,我可以从中读取。 I checked if it goes to bind - yes it goes with right resource value and with \\PDO::PARAM_LOB data type.我检查了它是否绑定 - 是的,它具有正确的资源值和\\PDO::PARAM_LOB数据类型。

I have an ActiveRecord class:我有一个 ActiveRecord 类:

class News extends ActiveRecord
{
    public function rules()
    {
        return [
            [
                ['image'],
                'image',
                'extensions' => 'png jpg',
                'maxSize' => 1024 * 300,
            ]
        ];
    }

    public function beforeSave($insert)
    {
        $fileInfo = UploadedFile::getInstance($this, 'image');
        $this->image = fopen($fileInfo->tempName, 'r+');
        return parent::beforeSave($insert);
    }

}

Table:桌子:

CREATE TABLE NEWS
(
    RN NUMBER(17,0) PRIMARY KEY NOT NULL,
    IMAGE BLOB
);

Logs showing this query:显示此查询的日志:

INSERT INTO "NEWS" ("IMAGE") VALUES (:qp4) RETURNING "RN" INTO :qp8

So it didn't actually bind it or what?所以它实际上并没有绑定它还是什么?

You should simply use image data instead of resource pointer, eg :您应该简单地使用图像数据而不是资源指针,例如:

$this->image = file_get_contents($fileInfo->tempName);

EDIT: sorry you are right, you need to provide a resource pointer to be able to bind this param using PARAM_LOB .编辑:抱歉,您说得对,您需要提供一个资源指针才能使用PARAM_LOB绑定此参数。

As stated on php doc , you should try using a transaction , eg :php doc 所述,您应该尝试使用事务,例如:

News::getDb()->transaction(function($db) use ($model) {
    $model->save();
});

It appears that PDO_OCI is working with Oracle in old-style way, so you need to start a transaction insert EMPTY_BLOB() first, then bind variable with pointer to file, execute statement and commit.看来 PDO_OCI 以旧式方式与 Oracle 一起工作,因此您需要先启动事务 insert EMPTY_BLOB() ,然后将变量与指向文件的指针绑定,执行语句并提交。

I've done it with update, because i don't want to make full query manually.我已经通过更新完成了,因为我不想手动进行完整查询。 First i write pointer to file into $this->file in save() method and call $model->save && $model->saveImage() in controller.首先,我在save()方法中将指向文件的指针写入$this->file并在控制器中调用$model->save && $model->saveImage()

public function saveImage()
{
    if (!$this->file) {
        return true;
    }
    $table = self::tableName();
    $rn = $this->rn;
    $command = Yii::$app->getDb()->createCommand(
        "UPDATE $table SET IMAGE=EMPTY_BLOB() WHERE RN=:rn RETURNING IMAGE INTO :image"
    );
    $command->bindParam(':rn', $rn, \PDO::PARAM_STR);
    $command->prepare();
    $command->bindParam(':image', $this->file, \PDO::PARAM_LOB);
    return $command->execute();
}

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

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