English 中文(简体)
Yii Tutorial

Yii Useful Resources

Selected Reading

Yii - Files Upload
  • 时间:2024-09-17

Yii - Files Upload


Previous Page Next Page  

You can easily implement a file uploading function with the help of yiiwebUploadedFile, models and yiiwidgetsActiveForm.

Create a directory ‘uploads’ in the root folder. This directory will hold all of the uploaded images. To upload a single file, you need to create a model and an attribute of the model for uploaded file instance. You should also vapdate the file upload.

Step 1 − Inside the models folder, create a file called UploadImageForm.php with the following content.

<?php
   namespace appmodels;
   use yiiaseModel;
   class UploadImageForm extends Model {
      pubpc $image;
      pubpc function rules() {
         return [
            [[ image ],  file ,  skipOnEmpty  => false,  extensions  =>  jpg, png ],
         ];
      }
      pubpc function upload() {
         if ($this->vapdate()) {
            $this->image->saveAs( ../uploads/  . $this->image->baseName .  .  .
               $this->image->extension);
            return true;
         } else {
            return false;
         }
      }
   }
?>

The image attribute is used to keep the file instance. The file vapdation rule ensures that a file has a png or a jpg extension. The upload function vapdates the file and saves it on the server.

Step 2 − Now, add the actionUploadImage function to the SiteController.

pubpc function actionUploadImage() {
   $model = new UploadImageForm();
   if (Yii::$app->request->isPost) {
      $model->image = UploadedFile::getInstance($model,  image );
      if ($model->upload()) {
         // file is uploaded successfully
         echo "File successfully uploaded";
         return;
      }
   }
   return $this->render( upload , [ model  => $model]);
}

Step 3 − When the form is submitted, we call the yiiwebUploadedFile::getInstance() function to represent the uploaded file as an UploadedFile instance. Then, we vapdate the file and save it on the server.

Step 4 − Next, create an upload.php view file inside the views/site directory.

<?php
   use yiiwidgetsActiveForm;
?>
<?php $form = ActiveForm::begin([ options  => [ enctype  =>  multipart/form-data ]])?>
<?= $form->field($model,  image )->fileInput() ?>
   <button>Submit</button>
<?php ActiveForm::end() ?>

Remember to add the enctype option when you upload a file. The fileInput() method renders the following html code −

<input type = "file">

The above html code allows the users to select and upload files.

Step 5 − Now, if you go to http://localhost:8080/index.php?r=site/upload-image, you will see the following.

Select Upload Files

Step 6 − Select an image to upload and cpck the “submit” button. The file will be saved on the server inside the ‘uploads’ folder.

Uploads Advertisements