如何在 yii2 高级模板中上传 web 文件夹中的文件? [英] How to upload files in web folder in yii2 advanced template?

查看:37
本文介绍了如何在 yii2 高级模板中上传 web 文件夹中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在后端上传文件,每次我上传文件时,它都会成功上传并成功保存在数据库中,但没有保存到我指定的目录中,因此我的应用程序找不到该文件,我已经为 web 目录中的上传文件夹授予了 777 权限.下面是我的代码

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

yii2 高级模板如何上传根目录下的文件?

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

负责上传的模型

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

<小时>

推荐答案

$path = '/uploads/';

这意味着您正在将文件上传到系统中的顶级文件夹 /uploads.

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

在终端中运行 cd/uploads 并检查,很可能文件已上传到那里.

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.

如果是高级应用,你已经有了@backend别名,所以你可以使用它:

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}");

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

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

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

然后像这样使用它:

Yii::getAlias('@uploads');

不要忘记包含 use Yii 如果你不在根命名空间或使用 \Yii;

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.

这篇关于如何在 yii2 高级模板中上传 web 文件夹中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆