PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 26, 2022

[FIXED] how to add uploded file name in to database using yii

 February 26, 2022     activerecord, php, yii, yii2     No comments   

Issue

I want to upload file with yii, I kinda did it. When I hit the submit button the file is saved in the folder where it should be. However, I want to add the filename to the database as well. How can I achieve this?

this is my controller :

public function actionUpload()
{
  $model = new TourImage();
  if (Yii::$app->request->isPost) {
    $model->imageFile = UploadedFile::getInstance($model, ‘imageFile’);
    if ($model->upload()) {
      // file is uploaded successfully
      return;
    }
  }
  return $this->render(‘upload’, [
  ‘model’ => $model
  ]);
  
}

Solution

You can extract the name of the original file from UploadedFile.getInstance() and assign it to the attribute of your model (This is normally done in your model "TourImage", in the upload method that you have had to implement).

Therefore if you have this in your controller action:

$model->imageFile = UploadedFile::getInstance($model, 'imageFile');

Then, in the upload() method of your TourImage model:

$this->your_model_attribute = $this->imageFile->name; // The original name of the file being uploaded

Change your_model_attributes to the attribute of your model where you want to save the file name.

Look at the public properties of the UploadedFile object: https://www.yiiframework.com/doc/api/2.0/yii-web-uploadedfile



Answered By - Dan A.S.
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing