I’m posting this by request from this thread;
It is usually recommended to store images in a server folder rather than in a database, but for small image files it can be preferable for ease and perhaps performance (see here) to store in them in the db. There may be a simple way to do this with ActiveRecord, but using Data Access Object (DAO) as shown below worked for me.
// View
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($image, 'org_image')->fileInput() ?>
// button and end form
// Model
//Validation rule
['org_image', 'file', 'extensions' => 'jpg, jpeg, gif, png', 'maxFiles' => 1, 'maxSize' => 1024 * 64, 'skipOnEmpty' => true, 'on' => 'org_image'],
//Method for upload
public function handleForm() {
if($_FILES['Image']['size']['org_image'] > 0) {
$fileName = $_FILES['Image']['name']['org_image'];
$tmpName = $_FILES['Image']['tmp_name']['org_image'];
$fileSize = $_FILES['Image']['size']['org_image'];
$fileType = $_FILES['Image']['type']['org_image'];
$content = fopen($tmpName, 'r');
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$q = 'INSERT INTO image (org_image, org_type, org_size) VALUES (:content, :type, :size)';
$cmd = Yii::$app->db->createCommand($q);
$cmd->bindValue(':content', $content, PDO::PARAM_LOB);
$cmd->bindValue(':type', $fileType, PDO::PARAM_STR);
$cmd->bindValue(':size', $fileSize, PDO::PARAM_INT);
$cmd->execute();
return $this;
}
}
// Controller
if ($image->load(Yii::$app->request->Post()) && $image->handleForm()) {
// return redirect ...
} else {
// return render form ...