简体   繁体   English

yii2将2个图像上传到不同的数据库字段

[英]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 ,它的工作原理

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

I defined $file2 in models file and added this line to _form 我在模型文件中定义了$ file2,并将此行添加到_form

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

And that's another part of my code in shopcontroller file 这是我在shopcontroller文件中的代码的另一部分

 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) . time()函数返回自Unix Epoch(1970年1月1日00:00:00 GMT)以来的秒数测量的当前时间。

If both files have the same ext and the diference in time between the 如果两个文件具有相同的ext和时间之间的差异

$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 并且您将两个文件写入相同的文件名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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