“跳空”不能在Yii2文件上传中工作

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了“跳空”不能在Yii2文件上传中工作脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有条款为我的申请中的公司上传徽标.上传和保存创建配置文件工作正常.但是在更新时,如果我不再上传它,徽标就会变空!

这是我的更新表格

<?PHP $form = ActiveForm::begin([
                'options' => ['enctyPE'=>'multipart/form-data']
        ]); ?>

       .....

       <?= $form->field($model,'logo')->fileinput() ?>

       ...

我的控制器动作

if ($model->load($_POST) ) {
    $file = \yii\web\UploadeDFile::getInstance($model,'logo');
    if($file){
    $model->logo=$file; }

    if($model->save()){

        if($file)
        $file->saveAs(\Yii::$app->basePath . '/web/images/'.$file);
        }

            return $this->redirect(['PRofile']);
        } else {
            return $this->renderPartial('update',[
                'model' => $model,]);
        }

我的规则:

public function rules()
{
    return [

        [['logo'],'image','extensions' => 'jpg,png','skIPOnEmpty' => true],[['name'],'required'],[['name','description'],'string'],];
}

有任何想法吗????

skipOnEmpty不适用于此处,因为在更新操作中,$model-> logo@L_126_13@不会为空,它将是一个带有文件名的字符串.$file仍然是一个只包含键的数组,但如果没有再次上传则不是值.所以检查$file->大小而不是检查!empty($file).通过修改控制器代码解决了以下问题!
$model = $this->findModel($id);
    $current_image = $model->featured_image;
    if ($model->load(Yii::$app->request->post())) {         
        $image= UploadedFile::getInstance($model,'featured_image');
        if(!empty($image) && $image->size !== 0) {
            //print_R($image);die;
            $image->saveAs('uploads/' . $image->baseName . '.' .$image->extension);
            $model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension; 
        }
        else
            $model->featured_image = $current_image;
        $model->save();
        return $this->redirect(['update','id' => $model->;module_id]);
    } else {
        return $this->render('add',[
            'model' => $model,]);
    }

脚本宝典总结

以上是脚本宝典为你收集整理的“跳空”不能在Yii2文件上传中工作全部内容,希望文章能够帮你解决“跳空”不能在Yii2文件上传中工作所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。