I'm trying to create a form with a text input and an upload file input using Angular6 for the client side and Yii2 for the server side.
Angular service:
create(name: string, image: any): Observable<any> {
let url = this.baseUrl + 'create';
let form: FormData = new FormData();
form.append('image', image);
form.append('name', name);
return this.http.post<Notification>(url, form);
}
Yii controller:
public function beforeAction($action)
{
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
public function actionCreate()
{
$model = new MapCreationFormModel();
if ($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
$response = MapRepository::create($model->name, $model->image);
return json_encode($response);
}
else
{
// >>> This exception is thrown.
throw new Exception("Cannot bind model");
}
}
Yii model:
class MapCreationFormModel extends Model
{
public $name;
public $image;
}
Using fiddler, I can see my request:
------WebKitFormBoundaryIv0dYBA9ZKwRHXlu Content-Disposition: form-data; name="image"; filename="test.bmp" Content-Type: image/bmp
BM [[[SPECIAL CHARACTERS]]]
------WebKitFormBoundaryIv0dYBA9ZKwRHXlu Content-Disposition: form-data; name="name"
aa
------WebKitFormBoundaryIv0dYBA9ZKwRHXlu--
Unfortunatelly, exception 'Exception("Cannot bind model")' from my controller is thrown (see controller code).
Do you have any idea why my model cannot be binded?
$model->errors
in else part to see the actual error that is preventing the loading of the attributes in the model from post array, try changing tothrow new Exception(implode(",",\yii\helpers\ArrayHelper::getColumn($model->errors,'0')));
and see what it says – Muhammad Omer Aslam$model->errors
in json and I displayed it in chrome console. I only have an empty string... Any idea? – C0b0ll{name: null, image: null}
. – C0b0llModelname[fieldname]
format . – Muhammad Omer Aslam