PHP code example of eluhr / yii2-fileflyupload

1. Go to this page and download the library: Download eluhr/yii2-fileflyupload library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

eluhr / yii2-fileflyupload example snippets


  namespace example\namespace\models;

  use eluhr\fileflyupload\traits\FileflyUploadTrait;
  use yii\base\Model;
  use yii\helpers\FileHelper;

  class MyModel extends Model
  {
      use FileflyUploadTrait;

      public $file;
      
      public function getLocalFs(): string {
          return 'fsLocal';
      }
      
      public function getStorageFs(): string {
          return 'fsStorage';
      }

      public function rules(): array
      {
          $rules = parent::rules();
          $rules[] = [
              'file',
              'file',
              'skipOnEmpty' => false,
              'extensions' => 'pdf',
              'maxSize' => 3145728 // 3 MB
          ];
          return $rules;
      }

      public function upload(): bool
      {
          if ($this->validate()) {
              $relativePath = '/path/to/file.pdf';
              $absolutePath = \Yii::$app->get($this->getLocalFs())->path . $relativePath;
              if (!FileHelper::createDirectory(dirname($absolutePath))) {
                  return false;
              }
              if ($this->file->saveAs($absolutePath) && $this->moveLocalFileToStorage($relativePath)) {
                  return true;
              }
              $this->addError('file', \Yii::t('model','Error while uploading file'));
          }
          return false;
      }
      
            
      public function beforeDelete()
      {
          if (!$this->deleteFromStorage('/path/to/file.pdf')) {
              return false;
          }
          return parent::beforeDelete();
      }
  }
 

  namespace example\namespace\controllers;

  use my\namespace\models\MyModel;
  use yii\web\Controller;
  use yii\web\UploadedFile;
  use Yii;

  class MyController extends Controller
  {
      public function actionUpload()
      {
          $model = new MyModel();
          if (Yii::$app->getRequest()->getIsPost()) {
              $model->file = UploadedFile::getInstance($model, 'file');
              if ($model->upload()) {
                  return $this->redirect(['upload']);
              }
          }
          return $this->render('upload', ['model' => $model]);
      }
  }
 

  use yii\helpers\Html;
  use yii\widgets\ActiveForm;

  $form = ActiveForm::begin();
  echo $form->field($model, 'file')->fileInput(['accept' => 'application/pdf']);
  echo Html::submitButton();
  ActiveForm::end();