7

I am implementing image upload in Yii2 using File Input Widget as shown in http://demos.krajee.com/widget-details/fileinput. May I know how to set the uploaded file size limit?

I have added:

['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1024],

inside the model's rules() but it does not seem to work.

Hope someone can advise. Thanks.

In View:

<?php $form = ActiveForm::begin(['enableClientValidation' => false,  'options' => [ 'enctype' => 'multipart/form-data']]); ?>


<?php

echo $form->field($model, 'image')->widget(FileInput::classname(), [
    'options'=>['accept'=>'image/*', 'multiple'=>true],
    'pluginOptions'=>['allowedFileExtensions'=>['jpg', 'jpeg', 'gif','png']]
]);

?>

<?php ActiveForm::end(); ?>

In Controller:

    $model = new IMAGEMODEL();  

    Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/PROJECT/';


    if ($model->load(Yii::$app->request->post())) {
        // get the uploaded file instance. for multiple file uploads
        // the following data will return an array
        $image = UploadedFile::getInstance($model, 'image');


        // store the source file name
        $model->FILENAME = $image->name;
        $ext = end((explode(".", $image->name)));

        // generate a unique file name

        $model->AVATAR = Yii::$app->security->generateRandomString().".{$ext}";
        $model->STD_ID=$_POST['IMAGEMODEL']['STD_ID'];


        // the path to save file, you can set an uploadPath
        // in Yii::$app->params (as used in example below)
        $path = Yii::$app->params['uploadPath'] . $model->AVATAR;

        if($model->save()){
            $image->saveAs($path);
            Yii::$app->session->setFlash('success', 'Image uploaded successfully');
            return $this->redirect(['view', 'id'=>$id]);

        } else {
            Yii::$app->session->setFlash('error', 'Fail to save image');
        }
    }

In Model:

public function rules()
{
    return [
        [['STD_ID', 'FILENAME'], 'required'],
        [['FILENAME'], 'string'],
        [['LAST_UPD_ON'], 'safe'],
        [['STD_ID'], 'string', 'max' => 50],
        [['LAST_UPDATE_BY'], 'string', 'max' => 150],

        [['image', 'FILENAME'], 'safe'],
        ['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1],

    ];
}
esiaz
  • 619
  • 4
  • 10
  • 22

3 Answers3

12

1) maxSize parameter expects number of bytes. In your example you set 1 Gb. For 2 Mb it should be:

['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 2],

2) Also check upload_max_filesize INI setting.

3) Make sure pass the instance of yii\web\UploadedFile by calling getInstance() method (for multiple files use getInstances()) before validate:

$this->image = UploadedFile::getInstance($this, 'image');
arogachev
  • 33,150
  • 7
  • 114
  • 117
  • Hi i tried but still is able to upload file sizes >2mb. The strange thing is when i check the $image = UploadedFile::getInstance($model, 'image'); $image->size returns me 0kb while all other parameters such as $image->name and $image->extension returns the correct values – esiaz Feb 04 '15 at 05:26
  • Show the rest of the code: how you handle uploaded image, how you display it in form. – arogachev Feb 04 '15 at 05:33
  • uploaded controller and view – esiaz Feb 04 '15 at 05:46
  • `'multiple' => true` - so you want upload multiple images or just one? – arogachev Feb 04 '15 at 05:51
  • at first the intention is to upload multiple but i get this in source code for chrome and for IE "
    Note: Your browser does not support file preview and multiple file upload. Try an alternative or more recent browser to access these features.
    " so i decided to go for just one for now
    – esiaz Feb 04 '15 at 05:55
  • In that case remove this option from plugin settings. – arogachev Feb 04 '15 at 05:56
  • have removed it so now it is echo $form->field($model, 'image')->widget(FileInput::classname(), [ 'options'=>['accept'=>'image/*'], 'pluginOptions'=>['allowedFileExtensions'=>['jpg', 'jpeg', 'gif','png']] ]); but still my 4mb file is able to upload successfully – esiaz Feb 04 '15 at 05:57
  • Try with regular file input without extensions. Also I don't get it - it allows you submit 4 Mb file or just upload it through extension before submitting? – arogachev Feb 04 '15 at 06:19
  • i retested, realise the 4mb file did not get uploaded to the server folder but the row was inserted into the database. How do i prevent insertion to the database if file is not uploaded to server? – esiaz Feb 04 '15 at 07:44
  • Current code should already prevent that, because you save file only after validation and saving record in database. – arogachev Feb 04 '15 at 08:04
  • is there any way i could check the size of the file and block it before saving? $image->size does not seem to cater to it. – esiaz Feb 04 '15 at 08:51
  • It's provided by PHP. See https://github.com/yiisoft/yii2/blob/master/framework/web/UploadedFile.php#L204 and https://github.com/yiisoft/yii2/blob/master/framework/web/UploadedFile.php#L217. I think the problem is somewhere else. This validation rule should work OK. – arogachev Feb 04 '15 at 08:56
  • my guess is my server is refusing entry for files>2mb. Am checking with my dba regarding this. the validation rule does not seem to have any effect on it, seems to be the same when i comment it off. The 4mb file still is refused entry. Is there any way i can display to user about file size exceeding limit set? – esiaz Feb 04 '15 at 09:04
  • i tried setting in rule ['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1], and uploaded a 1.46mb image, the file is uploaded successfully in server and database row added as well. The validation does not seem to be working. – esiaz Feb 04 '15 at 09:11
  • Have added here the rules set in my model. Can assist to see if anyting is wrong? – esiaz Feb 04 '15 at 09:14
  • I tested it just know and validation with maximum size work fine for me. Seems like the problem is somewhere else. – arogachev Feb 04 '15 at 09:23
  • After my dba updated the upload limit to 128mb on apache, i added: if($image->size >= 2097152) { Yii::$app->session->setFlash('error', 'Image exceed size limit'); return $this->redirect(['view', 'id'=>$id]);} solves the problem. Nevertheless thanks for your help~ – esiaz Feb 04 '15 at 09:26
  • You shouldn't do this check manually. Validator does it for you. You can see it here: https://github.com/yiisoft/yii2/blob/master/framework/validators/FileValidator.php#L216. Anyways glad to help. If the answer was helpful, don't forget to upvote and accept so the others can know too. – arogachev Feb 04 '15 at 09:32
  • If you want to change default error message for exceedeed file size, change `tooBig` parameter. – arogachev Feb 04 '15 at 09:34
  • 1
    ok thanks!.sorry but how do i implement validator in this case? – esiaz Feb 04 '15 at 09:41
  • What do you mean by "this case"? – arogachev Feb 04 '15 at 09:43
  • Exactly as in answer, just set proper `maxSize` instead of checking it manually. – arogachev Feb 04 '15 at 09:46
  • hi arogachev, can u kindly help me with http://stackoverflow.com/questions/28358398/how-to-implement-yii2-popover-x-on-gridview-view-and-update-button please? have been stuck with it for 2 days. Thanks! – esiaz Feb 07 '15 at 14:47
3

you can also set image dimension using this along with max file size

['image', 'image', 'minWidth' => 250, 'maxWidth' => 250,'minHeight' => 250, 'maxHeight' => 250, 'extensions' => 'jpg, gif, png', 'maxSize' => 1024 * 1024 * 2],

this allows you to upload maximum of 2mb with 250px width and 250px height

Shuhad zaman
  • 3,156
  • 32
  • 32
0

You can set in your view pluginOptions of the FileInput widget this property: 'maxFileSize' => 2048. It will be something like this:

widget(FileInput::classname(), [
    'options' => ['multiple'=>true, 'accept'=>'image/*'],

    'pluginOptions'=>[
        'allowedFileExtensions'=>['jpg','gif','png'],
        ...
        'maxFileSize' => 2048,
        ...
    ]
]);
tversteeg
  • 4,717
  • 10
  • 42
  • 77
Tsveti
  • 1
  • I am using "image extension", it works fine, as far as I upload images having size relatively small, like 2mbs etc it resize my image just the way i want, but problem starts when i upload big images having size 3mb or above, even my validation rules does not help me. I tried setting my upload_max_size to 256 Mb and memory limit to 512 Mb but when i try to upload a big image my page page just refresh. Is it a bug in framework or what. – Usman Iqbal Nov 22 '15 at 02:30