Home php yii2 saving uploaded image to database

yii2 saving uploaded image to database

Author

Date

Category

Good time of day
the question is how to attach an image to an article from the form.

I used the standard yii2 method;

Field imageFile;
in the database, in the same table created the imageFile field;

in my controller I have the following

if ($ model- & gt; load (Yii :: $ app- & gt; request- & gt; post () ) & amp; & amp; $ model- & gt; save ()) {
    $ model- & gt; imageFile = UploadedFile :: getInstance ($ model, 'imageFile');
    if ($ model- & gt; imageFile) {
      $ model- & gt; upload ();
    }
    return $ this- & gt; redirect (['view', 'id' = & gt; $ model- & gt; id]);

Boot Method – Standard

public function upload ()
{
  if ($ this- & gt; validate ()) {
    $ this- & gt; imageFile- & gt; saveAs ('uploads /'. $ this- & gt; imageFile- & gt; baseName. '.'. $ this- & gt; imageFile- & gt; extension);
    return true;
  } else {
    return false;
  }
}

Images from the form are loading fine, but when I see what comes in the post, in the field imageFile sting 0

and I need to bind the image that has loaded in the database.
Please tell me how to do this, or where to read, see.


Answer 1, authority 100%

You have implemented file loading, it remains to implement saving the name of this file to the database. For example, in the database you have the image field in the model, just declare the public field imageFile

class TableName extends ActiveRecord {
  public $ imageFile;
  ...

The controller has the following logic:

  • load $ _POST data into model
  • get file information (UploadedFile :: getInstance () )
  • validate the model
  • upload the file and add the file name to the base field
  • save model

Approximately:

if ($ model- & gt; load (Yii :: $ app- & gt; request- & gt; post () )) {
  $ model- & gt; imageFile = UploadedFile :: getInstance ($ model, 'imageFile');
  if ($ this- & gt; validate ()) {
    if ($ model- & gt; imageFile & amp; & amp; $ model- & gt; upload ()) {
      $ model- & gt; image = $ this- & gt; imageFile- & gt; baseName. '.' ... $ this- & gt; imageFile- & gt; extension;
    }
    if ($ this- & gt; save ()) {
      return $ this- & gt; redirect (['view', 'id' = & gt; $ model- & gt; id]);
    }
  }

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions