Umidjon Urunov
Umidjon Urunov

Reputation: 671

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(
        form.attr('action'),
        form.serialize()
        )
        .done(function(result){
            if(result == 1){
                form.trigger("reset");
                $.pjax.reload({container:'#products-table'});
                $.notify({
                    icon: "pe-7s-check",
                    message: "New product is added"

                },{
                    type: type[2],
                    timer: 10,
                    placement: {
                        from: 'top',
                        align: 'right'
                    }
                });

            }
            else {
                alert(result);
            }
        }).fail(function(){
        console.log("server error");
    });
    return false;
});

Upvotes: 1

Views: 3049

Answers (3)

SiZE
SiZE

Reputation: 2267

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

Upvotes: 1

Umidjon Urunov
Umidjon Urunov

Reputation: 671

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.

Upvotes: 1

RDK
RDK

Reputation: 4560

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

Upvotes: 0

Related Questions