Umidjon Urunov February 2016

Yii2 save image to database as base64

I am trying to save image as a base64 into database. But when I submit form I am getting the image NULL. I couldn't understand what's wrong.

VIEW:

<div class="content">
                <?php $form = ActiveForm::begin([
                    'id' => 'products-add-form',
                    'action' => ['products/product-add-form'],
                    'method' => 'post',
                    'options' => [
                        'class' => 'products-tbl-style',
                        'enctype' => 'multipart/form-data',
                    ]
                ]); ?>
                <?= $form->field($model, 'productName'); ?>
                <?= $form->field($model, 'cost'); ?>
                <?= $form->field($model, 'available')->dropDownList(['Y' => 'Yes', 'N' => 'No']); ?>
                <?= $form->field($model, 'image')->fileInput(['class'=>'btn btn-primary']); ?>
                <?= Html::submitButton('Save', ['class'=>'btn btn-success products-save-btn']); ?>
                <?php ActiveForm::end(); ?>
            </div>

Controller:

if($model->load(Yii::$app->request->post())){
    $file = UploadedFile::getInstance($model,'image');
    var_dump($file->name);
    var_dump($file);
    var_dump($_FILES);
}

Model:

public function rules()
    {
        return [
            [['productName', 'cost', 'available', 'image'], 'required'],
            [['cost'], 'number'],
            [['available'], 'string', 'max' => 1],
            [['image'], 'string'],
            [['productName'], 'string', 'max' => 100]
        ];
    }

Here my JQuery code, I am submitting the form data via ajax, does it cause a problem?

JS:

$("form#products-add-form").on('beforeSubmit', function(e){
    var form = $(this);
    $.post(
              

Answers


imRcH February 2016

You can try to use FileInput widget it work's perfectly.


SiZE February 2016

To send files via AJAX you shoud use FormData. To construct a FormData object that contains the data from an existing <form>, specify that form element when creating the FormData object:

$("form#products-add-form").on('beforeSubmit', function(e){
    $.post(
        form.attr('action'),
        new FormData(this) /* this is a form object */
    )
    /* your other code here */
});

UPD: As TS mentioned it should be processData set to false. It's impossible to set it for $.post, so we need to use $.ajax


Umidjon Urunov February 2016

I have tried following :

$.ajax( {
      url: 'http://host.com/action/',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
    e.preventDefault();

And now it's working, as @SiZE wrote, we need to send file input with FormData() via ajax.

Post Status

Asked in February 2016
Viewed 2,153 times
Voted 7
Answered 3 times

Search




Leave an answer