如何在yii2中上传php中的文件

时间:2017-12-13 08:02:47

标签: php yii2

我试图从后端上传pdf文件,但收到以下错误:

  

调用成员函数saveAs()以上载pdf文件

我的 _form 页面

<?= $form->field($model, 'pdf_file')->fileInput(['maxlength' => true]) ?>

我的控制器

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

    if ($model->load(Yii::$app->request->post())) {
          // echo "<pre>";print_r($_Files['image']);exit;
          $imageName = "special_image_".rand();
          $model->image = UploadedFile::getInstance($model,'image');

          if(!empty($model->image)){          

             $model->image->saveAs('images/gold/bangle/'.$imageName.'.'.$model->image->extension);

             $model->image = $imageName.'.'.$model->image->extension;
           }

             $pdfName = "my_pdf_".rand();

           if($model->pdf_file = UploadedFile::getInstance($model,'pdf_file')){          

                $model->image->saveAs('pdf/gold/'.$pdfName.'.'.$model->pdf_file->extension);

                $model->pdf_file = $pdfName.'.'.$model->image->extension;
            }

            if($model->save(false))
            {
                return $this->redirect(['view', 'id' => $model->id]);

            }
            else
            {
                       return $this->render('create', [
                'model' => $model,
            ]);

            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

1 个答案:

答案 0 :(得分:0)

1)通过添加enctype来确保您的文件发布:

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

2)将规则文件添加到您的规则中:

[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],

3)获取模型实例

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

4)使用saveAs

$model->imageFile->saveAs('uploads/' . $this->imageFile->baseName)