如何在yii2高级模板中上传web文件夹中的文件?

时间:2016-01-14 20:52:04

标签: yii2

我尝试在后端上传文件,每次上传文件时都成功上传并成功保存在数据库中但是它没有保存到我指定的目录中,所以我的应用程序无法找到文件,我已经给了web目录中uploads文件夹的777权限。下面是我的代码

处理和保存文件上传的模型......

如何在yii2高级模板的根文件夹中上传文件?

负责上传的模型

<?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;
        }

    }

}

产品模型负责将信息保存到数据库

<?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

1 个答案:

答案 0 :(得分:1)

$path = '/uploads/';

这意味着您要将文件上传到系统中顶级文件夹/uploads

在终端中运行cd /uploads并检查,很可能是在那里上传了文件。

要解决此问题,您需要指定正确的完整路径。推荐的方法是使用别名。

如果是高级应用程序,您已经拥有@backend别名,因此您可以使用它:

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

或者在common/config/bootstrap.php中创建自己的别名:

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

然后像这样使用它:

Yii::getAlias('@uploads');

如果您不在根命名空间中或使用use Yii,请不要忘记添加\Yii;

如果您希望可以在前端访问图像,可以在前端和后端图像文件夹之间创建符号链接。