Home  >  Article  >  PHP Framework  >  File upload and download in Yii framework: implement file-related operations

File upload and download in Yii framework: implement file-related operations

王林
王林Original
2023-06-21 09:44:26984browse

Yii framework is an MVC framework based on PHP language. Its main features are rapid development, simplicity and efficiency. In website development, file uploading and downloading are a common function. This article will introduce how to implement file uploading and downloading in the Yii framework.

1. File upload

1. Preparation work

Before uploading files, we need to perform relevant configurations first. Open the config/main.php file and add the following code to the component:

'components' => [
      'request' => [
        'parsers' => [
          'application/json' => 'yiiwebJsonParser',
          'multipart/form-data' => 'yiiwebMultipartFormDataParser',
        ],
      ],
        'request' => [
        'enableCsrfCookie' => false,
        'enableCsrfValidation' => false,
        'parsers' => [
          'multipart/form-data' => 'yiiwebMultipartFormDataParser',
        ],
      ],
        'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
        ],
      ],
 
  ],

Add two request parameters to the component, namely parsers and enableCsrfValidation. parsers is the parser of the request. Adding multipart/form-data indicates that uploading files is allowed. enableCsrfValidation means turning off CSRF verification.

2. Implement file upload

To implement file upload in the controller, you can choose form submission or Ajax upload. Here we take form submission as an example.

public function actionUpload()
    {
        $uploadModel = new UploadForm();
 
        if (Yii::$app->request->isPost) {
            $uploadModel->file = UploadedFile::getInstance($uploadModel, 'file');
            if ($uploadModel->upload()) {
                // file is uploaded successfully
                return;
            }
        }
 
        return $this->render('upload', ['model' => $uploadModel]);
    }

In actionUpload, a model class UploadForm for uploading files is instantiated. At the same time, Yii::$app->request->isPost is used to determine whether it is a POST request. If so, the Yii::$app->request->getInstance() method is used to obtain the file information, and Call the upload() method to upload files. Returns true if the upload is successful, false if it fails.

The implementation code of the UploadForm class is as follows:

class UploadForm extends yiiaseModel
    {
        /**
         * @var UploadedFile file attribute
         */
        public $file;
 
 
        /**
         * @return array the validation rules.
         */
        public function rules()
        {
            return [
                [['file'], 'file'],
            ];
        }
 
        public function upload()
        {
            if ($this->validate()) {
                $filePath = 'uploads/' . $this->file->baseName . '.' . $this->file->extension;
                $this->file->saveAs($filePath);
                return true;
            } else {
                return false;
            }
        }
    }

In UploadForm, a public attribute file is set to store uploaded files. At the same time, a rules method is set up to verify the file, and upload the file after passing the verification. The path for file upload is 'uploads/' . $this->file->baseName . '.' . $this->file->extension.

3. Implement file download

The file download function is relatively simple to implement, just return the file stream directly in the controller.

public function actionDownload($file)
    {
        Yii::$app->response->sendFile($file);
    }

In actionDownload, use the Yii::$app->response->sendFile() method to return the file stream. Where $file is the file path.

2. Summary

This article introduces how to implement the file upload and download functions in the Yii framework, mainly involving the related configuration, operation and design of related models for file upload and download. Through the study of this article, we will have a deeper understanding and familiarity with file operations in the Yii framework, and implement related functions more conveniently and quickly.

The above is the detailed content of File upload and download in Yii framework: implement file-related operations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn