How to upload a file to directory in yii2?

后端 未结 6 1187
再見小時候
再見小時候 2020-12-09 08:57

i have an ActiveForm, and i want to add a field where the user can upload their photos. the problem is that i don\'t have an attribute for the image in the users table and e

6条回答
  •  一生所求
    2020-12-09 09:24

    I really like Yii2 Dropzone.

    Installation:

    composer require --prefer-dist perminder-klair/yii2-dropzone "dev-master"
    

    Usage:

     [
               'url'=> Url::to(['resource-manager/upload']),
               'paramName'=>'image',
               'maxFilesize' => '10',
           ],
           'clientEvents' => [
               'complete' => "function(file){console.log(file)}",
               'removedfile' => "function(file){alert(file.name + ' is removed')}"
           ],
       ]);
    
       ?>
    

    Controller:

    public function actionUpload(){
    
            $model = new ResourceManager();
            $uploadPath = Yii::getAlias('@root') .'/uploads/';
    
            if (isset($_FILES['image'])) {
                $file = \yii\web\UploadedFile::getInstanceByName('image');
              $original_name = $file->baseName;  
              $newFileName = \Yii::$app->security
                                ->generateRandomString().'.'.$file->extension;
               // you can write save code here before uploading.
                if ($file->saveAs($uploadPath . '/' . $newFileName)) {
                    $model->image = $newFileName;
                    $model->original_name = $original_name;
                    if($model->save(false)){
                        echo \yii\helpers\Json::encode($file);
                    }
                    else{
                        echo \yii\helpers\Json::encode($model->getErrors());
                    }
    
                }
            }
            else {
                return $this->render('upload', [
                    'model' => $model,
                ]);
            }
    
            return false;
        }
    

提交回复
热议问题