3

my controller file inside api/v1/controller/

class ProfileController extends ActiveController
  {
    public $modelClass = 'app\models\Profile';

    public function behaviors()
    {
        return [
            [
                'class' => 'yii\filters\ContentNegotiator',
                'only' => 
                         ['index', 'view', 'createnew','update','search'],
                'formats' => 
                         ['application/json' => Response::FORMAT_JSON,],

            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'index' => ['get'],            
                    'view' => ['get'],            
                    'createnew' => ['post'],       
                    'update' => ['put'],         
                    'delete' => ['delete'],        
                    'deleteall' => ['post'],
                    'search' => ['get']
                ],

            ]
        ];
    }

    public function actionCreatenew() {
        $model = new Profile();
        $model->load(Yii::$app->request->post());



        $model->asset = UploadedFile::getInstance($model, 'asset');
     
        $name = $model->user_id;

        if($model->asset) {
            
          $model->asset->saveAs('uploads/'.$name.'.
                           '.$model->asset->extension);
            $model->asset = $model->asset->name.'.'.
                            $model->asset->extension;
           
        }



        if($model->save()) {
            echo json_encode(array('status'=>"Success",
                     'data'=>$model->attributes),JSON_PRETTY_PRINT);
        } else {
            echo json_encode(array('status'=>"Failure",
                     'error_code'=>400,
                     'errors'=>$model->errors),JSON_PRETTY_PRINT);
        }
    }

}

When I try to use access this from Postman like: POST http://localhost/myapp/api/v1/profiles

I get Invalid Parameter – yii\base\InvalidParamException

Response content must not be an array.

What is the issue?? help would be grateful!! Thanks

1
  • I have fixed the issue by adding this in my api/config.php file ''urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/country','v1/profile'], 'extraPatterns' => [ 'POST createnew' => 'createnew', ], ], ], ],' Commented May 13, 2016 at 6:56

2 Answers 2

10

You can easily receive single / multi-uploaded files using HTTP POST with form-data encoding in Yii2, directly in your Yii2 Controller / action.

Use this code:

    $uploads = UploadedFile::getInstancesByName("upfile");
    if (empty($uploads)){
        return "Must upload at least 1 file in upfile form-data POST";
    }

    // $uploads now contains 1 or more UploadedFile instances
    $savedfiles = [];
    foreach ($uploads as $file){
        $path = //Generate your save file path here;
        $file->saveAs($path); //Your uploaded file is saved, you can process it further from here
    }

If you use Postman API client to test how your API is working, you can configure the upload endpoint to work like this for multi-file uploads:

Body form-data params for POST data request

Note: The upfile[] square brackets are important! Postman will happily let you select multiple files for upload in one slot, but this will not actually work. Doing it the way shown in the screenshot makes an array of files available to the Yii2 action, through the UploadedFile mechanism. This is roughly equivalent to the standard PHP $_FILES superglobal variable but with easier handling.

Single files can be uploaded with or without the [] square brackets after the key name. And of course you can name upfile whatever you like, for your convention.

Sign up to request clarification or add additional context in comments.

Comments

1

You should use \yii\web\UploadedFile::getInstanceByName('asset'); instead of getInstance() checkout this Link

3 Comments

Thanks for this(added as you mentioned) .But I'm getting "Response content must not be an array." not for this I believe.
In which line? why are you echoing json string? you can simple use return ['status'=>'success','data'=>$model->attributes];
I have fixed the issue by adding this in my api/config.php file ''urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/country','v1/profile'], 'extraPatterns' => [ 'POST createnew' => 'createnew', ], ], ], ],'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.