0
votes

I am trying to upload the image from postman form-data. I cant get the input

 URL: localhost/sampleyii/web-app/web/imageuploads
 Method: POST
 {"Content-Type":"application/x-www-form-urlencoded"}
 Form-data
  id : 2
  image : test.jpg (type:file)   

In my yii coding:

 $model = new TblImgUpload(); 
 print_r(Yii::$app->request->post());
 $model->load(Yii::$app->request->post(),'');

Response from postman:

Array
 (
[------WebKitFormBoundarySHaGMA86OHQV87iT
Content-Disposition:_form-data;_name] => "id"

sdfgdfgdf
------WebKitFormBoundarySHaGMA86OHQV87iT
Content-Disposition: form-data; name="wretr"; filename="test.jpeg"
Content-Type: image/jpeg........
....................

I have tried Content-Type => 'multipart/form-data'. But i cant get the input request.

I want the post request input as form-data (file) as array.

Please help thanks in advance.

2

2 Answers

0
votes

$model->load() need post values with specific name. So in you postman call 'id' must be 'TblImgUpload[id]' and 'image' must be 'TblImgUpload[image]'.

Note that 'id' and 'image' must be returned as 'safe' attributes in the rules method of the model or they will not be loaded in any massive way.

0
votes

Use Either yii\web\UploadedFile::getInstance() or yii\web\UploadedFile::getInstanceByName() to retrieve the uploaded file. There is a good example on how to acheive it in official docs.

Here is a quick snippet code I've used once for a REST app:

Controller:

use Yii;
use yii\web\UploadedFile;
use app\models\UploadImageForm;

class UploadController extends ActiveController
{

  public function actionImage()
  {
      $model = new UploadImageForm(); 

      if (Yii::$app->request->isPost) {
          $model->load(Yii::$app->getRequest()->getBodyParams(), '');
          $model->imageFile = UploadedFile::getInstanceByName('imageFile'); 
          /**
           * Note: when validation fails, returning the model itself 
           * will output the failing rules on a '422' response status.
          **/
          return $model->upload() ?: $model;
      }
  }

}

Model:

use Yii;
use yii\helpers\Url;
use yii\web\ServerErrorHttpException;


class UploadImageForm extends \yii\base\Model
{
    public $imageFile;
    public $documentPath = 'uploads/';

    public function rules()
    {
        return [
            [['imageFile'], 'required'],
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg',  'maxSize' => 4194304, 'tooBig' => 'File size limit is 4MB'],
        ];
    }

    public function attributes()
    {
        return ['imageFile'];  
    }


    public function upload()
    {
        if ($this->validate()) {

            $fileName = $this->imageFile->baseName . '.' . $this->imageFile->extension;
            $path = $this->documentPath . Yii::$app->user->id . '/';

            if ($this->imageFile->saveAs($path.$fileName) === false)
                throw new ServerErrorHttpException('Failed for unknown reason. please try again');

            return [
                'imagePath' => Url::to('@web', true) .'/'. $path.$fileName, 
            ];
        } 

        return false;
    }
}