How to get filetype and size of uploaded image with Yii

7.1k views Asked by At

I have a problem with Yii:

I have a Model called Slider.php and a controller called SliderController.php .

I wrote this code to make the user upload an image:

public function actionCreate()
{
    $model=new Slider;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);



    if(isset($_POST['Slider']))
    {
        $model->attributes=$_POST['Slider'];
        $model->image=CUploadedFile::getInstance($model, 'image');
        if($model->save()) {
            if(strlen($model->image)>0)
            {
                $model->image->saveAs(Yii::app()->basePath.'/../uploads/slider/'.$model->image);
            }


            $this->redirect(array('view','id'=>$model->id));
        }
    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

and it works fine.

My question is: how can I get/return the filetype and the size in the view?

2

There are 2 answers

2
Jon On

CUploadedFile has size and type attributes that you can use. Since the information is inside $model->image, you can access it in the view with

Size: <?= $model->image->size; ?>
Type: <?= $model->image->type; ?> 

Note that the type above is reported by the client, so with a misconfigured client (either deliberately or by accident) it will not be accurate. For display purposes this will not really matter, but if you are storing the MIME type somewhere for later use you should determine it on the server side with CFileHelper::getMimeType.

0
Dyego Nery On

You also can get the extension name using $model->image->getExtensionName(). This method returns the name of file extension. Check the documentation in the link below.

http://www.yiiframework.com/doc/api/1.1/CUploadedFile#getExtensionName-detail