Speaktech.in

Upload image in Yii 2 REST API

In this article we will see how to upload image using REST API in yii2 application.

use yii\web\UploadedFile;
use yii\helpers\Url;

publicfunctionactionSinglefile()

{

  Yii::$app->response->format = Response::FORMAT_JSON;

  $uploadedFile = UploadedFile::getInstanceByName('profile_image');


   if ($uploadedFile) {
               //get the uploaded file name
               $filename = $uploadedFile->name;
               //pathinfo() returns more info about the $uploadFile
               $pathinfo = pathinfo($uploadedFile);
               //create a new filename to avoid file collission
               $filename = $pathinfo['filename'].'_'.date('YmdHis').rand(10000,99999);
               //get extension
               $extension  = $uploadedFile->getExtension();
               //directory to save the image
               $save_path = Yii::getAlias('@frontend') .'/uploads/' ;
               //check if dir already exists
               if (!file_exists($save_path)) {
                   //make dir ,give permissions
                     mkdir($save_path, 0777, true);
                   }
                   //save file
                 $uploadedFile->saveAs($save_path . $filename. '.' . $extension);
              }

             Yii::$app->response->statusCode = 200;
               $response = array(
                   'profile' =>'Upload success',
               );
              return $response;

}