sam
sam

Reputation: 956

How to upload files in web folder in yii2 advanced template?

I try to upload files in backend and each time i uploaded a file it was successfully uploaded and successfully saved in the DB but it wasn't save to the directory i specified so my application can't find the file, and i already gave 777 permission to the uploads folder in web directory. below is my codes

Model to handle and save the file upload...

How to upload files in root folder in yii2 advanced template?

Model responsible for the upload

<?php

namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;


class UploadForm extends Model {

    public $img;
    public $randomCharacter;


    public function rules(){
        return[
             [['img'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
        ];
    }
    public function upload(){
        $path = '/uploads/';
        $randomString = '';
        $length = 10;
          $character = "QWERTYUIOPLKJHGFDSAZXCVBNMlkjhgfdsaqwertpoiuyzxcvbnm1098723456";
            $randomString = substr(str_shuffle($character),0,$length);
              $this->randomCharacter =  $randomString;
          if ($this->validate()){
            $this->img->saveAs($path .$randomString .'.'.$this->img->extension);
            return true;
        }else{
            return false;
        }

    }

}

The product model reponsible for save info into database

<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;


class Products extends \yii\db\ActiveRecord
{



    public static function tableName()
    {
        return 'products';
    }


    public function rules()
    {
        return [

            [['name'], 'string', 'max' => 100],
            [['descr', 'img', 'reviews'], 'string', 'max' => 255],
           // [['file'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg']

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [

            'img' => 'Img',

        ];
    }




}

my controller and the action
 public function actionCreate()
    {

      $time = time();

        $model = new Products();
        $upload = new UploadForm();

          if ($model->load(Yii::$app->request->post()) ) {
            //get instance of the uploaded file
               $model->img = UploadedFile::getInstance($model, 'img');
                 //define the file path
                    $upload->upload();
                     //save the path in the db
                        $model->img = 'uploads/' .$upload->randomCharacter .'.'.$model->img->extension;
                           $model->addtime = $time;
                               $model->save();
                     return $this->redirect(['view', 'product_id' => $model->product_id]); 

            }else {
                return $this->render('create', [
                'model' => $model,
              ]);

            }



        }

and my view file has been modified too thanks for any help

Upvotes: 0

Views: 2919

Answers (1)

arogachev
arogachev

Reputation: 33538

$path = '/uploads/';

That means you are uploading files to /uploads, the top level folder in the system.

Run cd /uploads in your terminal and check, most likely files were uploaded there.

To fix that, you need to specify correct full path. The recommended way to do it is using aliases.

In case of advanced application, you already have @backend alias, so you can use it:

$this->img->saveAs(\Yii::getAlias("@backend/web/uploads/{$randomString}.{$this->img->extension}");

Or create your own alias in common/config/bootstrap.php:

Yii::setAlias('uploads', dirname(dirname(__DIR__)) . '/backend/web/uploads');

And then use it like this:

Yii::getAlias('@uploads');

Don't forget to include use Yii if you are not in root namespace or use \Yii;

If you want your images to be accessible on frontend, you can create symlink between frontend and backend images folders.

Upvotes: 1

Related Questions