0

I was trying to upload pdf file from backend but I receive the following error:

Call to a member function saveAs() for uploading pdf file

My _form page

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

My controller

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,
            ]);
        }
    }
2

1 Answer 1

0

1) make sure your file is post by adding enctype:

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

2) add rule file to your rules like this:

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

3) Get Instance for model

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

4) use saveAs

$model->imageFile->saveAs('uploads/' . $this->imageFile->baseName)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.