Rimsha Fatima
Rimsha Fatima

Reputation: 13

how to make a post request in yii without form?

i want to send image in database using url. but it is sending null value. please guide me about this. i want to make an api which will be use to upload image

public function actionTest()
{
    $model = new Users;

    if(isset($_POST['Users']))
    {
       $model->image=$_POST['Users']['image'];

        $model->image=CUploadedFile::getInstance($model,'image');
         echo $model->image;
        echo 'hello';
        if(is_object($model->image)){
            //mkdir(getcwd().'/images/users/' . $model->id."/");
            $name = getcwd().'/images/' .$model->id."/".$model->image->getName();

            $model->image->saveAs($name);
            try{
            $image = Yii::app()->image->load($name);
            $image->resize(50, 50);
            $image->save();
            }
            catch(Exception $ex ){
                 echo 'image has been saved successfully';
            die;
            }
        }
    }
}

Upvotes: 1

Views: 635

Answers (1)

Igor Savinkin
Igor Savinkin

Reputation: 6277

The simpler the better... I think you'd better use standard Yii fileField() in form.

In view:

<?php $form=$this->beginWidget('CActiveForm', array(
 'enableAjaxValidation'=>false,
 'enableClientValidation'=>false,
 'htmlOptions' => array(
    'enctype' => 'multipart/form-data',
 ),
)); ?>
...

<?php echo $form->labelEx($model,'image'); ?> 
<?php echo $form->fileField($model,'image',array('size'=>40,'maxlength'=>255)); ?>
<?php echo $form->error($model,'image'); ?>
<br><br>
<?php echo CHtml::submitButton(  Yii::t('general','Create')  ); ?>

<?php  // show image if it already exists in file system
 if ((getimagesize(Yii::app()->basePath. '/../img/foto/'. $model->article . '.jpg') !== false) ) : ?> 
<?php echo CHtml::image(Yii::app()->baseUrl. '/img/foto/'. $model->article . '.jpg')?> 
<?php endif;    ?>

<?php $this->endWidget(); ?>

Notice 'enctype' => 'multipart/form-data' in the form html settings. This makes it to upload file. Then on a controller side you apply your file catch and store

As far as a model side I recommend to closely follow this tutorial.

If you try to do smth. without form you'll waste time inventing bycicle.

Upvotes: 1

Related Questions