dongmeng4742
dongmeng4742
2015-09-11 11:29
浏览 50

Yii2将文件保存到Oracle BLOB

Problem is that i can't save file to 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.

I have an ActiveRecord class:

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpinken0498
    dongpinken0498 2015-09-14 15:01
    已采纳

    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.

    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.

    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();
    }
    
    点赞 评论
  • duandi5328
    duandi5328 2015-09-11 11:39

    You should simply use image data instead of resource pointer, e.g. :

    $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.

    As stated on php doc, you should try using a transaction, e.g. :

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

相关推荐