Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file to server via POST API in Yii2.0?

Tags:

php

yii2

I make a model in yii2 from this link http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html I post the file using POST request to API and got all file information in my controller but unable to upload file using this Yii2.0 model created using above link normal PHP file upload code work fine. Here is my controller code

public function actionUploadFile()
    {
        $upload = new UploadForm();
        var_dump($_FILES);

        $upload->imageFile = $_FILES['image']['tmp_name'];
        //$upload->imageFile = $_FILES;
        var_dump($upload->upload());
    }

and my model code is

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

    public function rules()
    {
        return [
            [['imageFile'], 'safe'],
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    public function upload()
    {
        try {
            if ($this->validate()) {
                $this->imageFile->saveAs('/var/www/html/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
                var_dump("Jeree");
                return true;
            } else {
                var_dump($this->getErrors());
                return false;
            }
        }catch (ErrorException $e) {
            var_dump($e->getMessage());
        }
    }
    }
like image 710
Anway Kulkarni Avatar asked Oct 19 '22 00:10

Anway Kulkarni


1 Answers

Try this way

public function actionUpload()
{
   $model = new UploadForm();

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

       if ($model->validate()) {                
          $model->file->saveAs('/var/www/html/' . $model->file->baseName . '.' . $model->file->extension);
       }
    }

    return $this->render('upload', ['model' => $model]);
}
like image 96
ScaisEdge Avatar answered Oct 29 '22 04:10

ScaisEdge