简体   繁体   中英

yii2 upload 2 images to different database fields

I already have a file upload page and it works properly, but I need to create another field to upload another Image and its not working..

This is in my _form and it works

<?= $form->field($model, 'file')->fileInput(['onchange'=>'readURL(this)'])->label(false) ?>

I defined $file2 in models file and added this line to _form

<?= $form->field($model, 'file2')->fileInput(['onchange'=>'readURL(this)'])->label(false) ?>

And that's another part of my code in shopcontroller file

 if ($model->load(Yii::$app->request->post()) ) {


             $model->file    =   UploadedFile::getInstance($model, 'file');
             $model->file2   =   UploadedFile::getInstance($model, 'file2');

                    if($model->file!='')
                    {

                        $model->ShopLogo  =  time().'.'.$model->file->extension;

                    }

                    if($model->file2!='')
                    {

                        $model->pic=  time().'.'.$model->file2->extension;

                    }

Another part of the Code

                $dir = 'web/shop/'.$model->Id;

                if($model->file!='')
                {
                    if(!file_exists($dir))
                    {
                        mkdir($dir);

                    }

                    $model->file->saveAs($dir."/". $model->ShopLogo);
                } 

                if($model->file2!='')
                {
                    if(!file_exists($dir))
                    {
                        mkdir($dir);

                    }

                    $model->file2->saveAs($dir."/". $model->pic);

                 }

What can I do to fix it ?

the time() function returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) .

If both files have the same ext and the diference in time between the

$model->ShopLogo  =  time().'.'.$model->file->extension;

and

$model->pic=  time().'.'.$model->file2->extension; 

is less than a sec and

$model->ShopLogo = $model->pic

and you are writing both files to the same filename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM