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

混江龙づ霸主 提交于 2019-12-18 04:23:32

问题


I am unable to upload files in root folder.

I uploaded files in root folder and access these files in frontend and backend application.


回答1:


When using the advanced template you need to decide on a common place to store your files that can be accessed by both the frontend and backend application, additionally if you want the files to be publicly accessible via the web you need to insure this location is a public folder.

I tend to use the frontend/web folder as my common upload location. When uploading from the backend I write to this location. I can then use the images in the frontend.

Example uploading form the backend.

UploadForm.php

Create a model to manage the upload data, make sure to include the file attribute.

class UploadForm extends Model
{
    /**
     * @var UploadedFile file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file', 'extensions'=>'jpg, gif, png'],
        ];
    }
}

UploadController

In the controller that will be managing the upload use the alias for the frontend to set your upload path $path = Yii::getAlias('@frontend') .'/web/uploads/'

class MediaController extends Controller
{

    public function actionIndex()
    {

        $model = new UploadForm();

        //Set the path that the file will be uploaded to
        $path = Yii::getAlias('@frontend') .'/web/upload/'

        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $model->file->saveAs($path . $model->file->baseName . '.' . $model->file->extension);
            }
        }

        return $this->renderPartial('index', ['model' => $model]);

    }
}

View Form

Add a form to your view, make sure to set the 'multipart/form-data' enctype so that it can accept file uploads.

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']) ?>

    <?= $form->field($model, 'file')->fileInput(); ?>

    <?= Html::submitButton('Upload') ?>

<?php ActiveForm::end() ?>

Front End

You can then access the image in the front end via /upload/{image-name}.{extension}. example <img src="/upload/sample.png">

Note: it is a good idea to store your upload path in the common/config/params.php so that you can access from both frontend and backend.




回答2:


Here is complete solution of image uploading,updating, deleting an image. Please follow the steps carefully.

1 Create uploads folder in your root directory.

2 Root Alias in Yii2

Open you common/config/bootstrap.php and add this line top of the file

Yii::setAlias('@root', realpath(dirname(__FILE__).'/../../'));

---

3 Model:

public function rules()
    {
    return [

        ['image', 'image', 
                    'skipOnEmpty' => true, 
                    'extensions' => 'jpg, gif, png']

        ];
    }

4 File Input

<?php
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

    <?= $form->field($model, 'image')->fileInput() ?>

    <button>Submit</button>

<?php ActiveForm::end() ?>

5 Controller action

 class PostController extends Controller
   {
       public function actionCreate()
       {
        $model = new Post();
        if ($model->load(Yii::$app->request->post())) {            
            $file = \yii\web\UploadedFile::getInstance($model, 'image');
            if (!empty($file))
                $model->image = $file;

            if($model->save())
            {
             if (!empty($file))
              $file->saveAs( Yii::getAlias('@root') .'/uploads/' . $file);

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

       public function actionUpdate($id)
       {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())){           
            $file = \yii\web\UploadedFile::getInstance($model, 'image');
           if (!empty($file)){
                 $delete = $model->oldAttributes['image'];
                 $model->image= $file; 
            }
            else{
                $model->image = $model->oldAttributes['image'];
            }
            if($model->save())
            {
             if (!empty($file))
              $file->saveAs( Yii::getAlias('@root') .'/uploads/' . $file);

              return $this->redirect(['view', 'id' => $model->id]);
            }
            return $this->render('update', ['model' => $model]);
        } else {
            return $this->render('update', ['model' => $model]);
        }
    }

       public function actionDelete($id)
       {
        $model = $this->findModel($id);
        if(file_exists(Yii::getAlias('@root') . '/uploads/'. $model->image))
        unlink(Yii::getAlias('@root') . '/uploads/'. $model->image);
        $model->delete(); 
         return $this->redirect(['index']);
       }

  }

Edit:

6 Show in Gridview(Backend)

[
'attribute' => 'image',
'format' => 'html',    
'value' => function ($data) {
    return Html::img('../../../uploads/'. $data['image'],
        ['width' => '70px']);
 },
],

7 Show in DetailView(Backend)

   [
      'attribute'=>'image',
      'label'=> 'Post Picture',
      'value'=> '../../../uploads/' . $model->image,
      'format'=>['image',['width'=>100, 'height'=>100]]
    ],

if you have hide frontend/web then add this rule in your project root (yii2-app) .htaccess file:

RewriteEngine on

  RewriteCond %{REQUEST_URI} /(uploads)
  RewriteRule ^uploads/(.*)$ uploads/$1 [L]

Show image in frontend

 <img src="<?php echo 'uploads/'.$model->image; ?>">


来源:https://stackoverflow.com/questions/28493615/how-to-upload-files-in-root-folder-in-yii2-advanced-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!