0
votes

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?

1
you should check for the $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 to throw new Exception(implode(",",\yii\helpers\ArrayHelper::getColumn($model->errors,'0'))); and see what it saysMuhammad Omer Aslam
I put $model->errors in json and I displayed it in chrome console. I only have an empty string... Any idea?C0b0ll
When I display the model in Chrome console, I have {name: null, image: null}.C0b0ll
you should submit the input name with the model like Modelname[fieldname] format .Muhammad Omer Aslam

1 Answers

1
votes

I finally found my problem with this post: Yii2 POST image to model in API without Yii2 Naming convention.

I have to use method UploadedFile::getInstanceByName.

Here is my code for interested people:

public function actionCreate()
{
    $name = Yii::$app->request->post('name'); 
    $fileData = UploadedFile::getInstanceByName('image');
    $fileName = time() . '.' . $fileData->extension;
    $filePath = '../uploads/' . $fileName;
    $fileData->saveAs($filePath);
    $image = fopen($filePath,"rb");
    // Do your stuff.
}