YII2檔案上傳驗證,簡單封裝

WindHoney發表於2019-02-16

上傳使用FileInput外掛
官方文件 http://demos.krajee.com/widge…
也參考了 http://www.manks.top/yii2_mul…
外掛引數比較多。前臺表單部分,可以參照具體例子寫就行了。

主要是上傳之後的處理和驗證,驗證檔案的型別,大小等,我寫了一個公共方法來處理上傳

/**
     * 檔案上傳
     * ```
     *  $model = new UploadValidate($config_name);
     *  $result = CommonHelper::myUpload($model, $field, `invoice`);
     * ```
     *
     * @param  object $model commonmodelsUploadValidate 驗證上傳檔案
     * @param  string $field 上傳欄位名稱
     * @param  string $path  檔案儲存路徑
     *
     * @return bool|array
     */
    public static function myUpload($model, $field, $path = ``)
    {
        $upload_path = Yii::$app->params[`upload_path`];
        $path = $path ? $path . "/" : ``;
        if (Yii::$app->request->isPost) {
            $file = UploadedFile::getInstanceByName($field);
            $model->file = $file;
            //檔案上傳存放的目錄
            $dir = $upload_path . $path . date("Ymd");
            if ( !is_dir($dir)) {
                mkdir($dir, 0777, true);
                chmod($dir, 0777);
            }
            if ($model->validate()) {
                //生成檔名
                $rand_name = rand(1000, 9999);
                $fileName = date("YmdHis") . $rand_name . `_` . $model->file->baseName . "." . $model->file->extension;
                $save_dir = $dir . "/" . $fileName;
                $model->file->saveAs($save_dir);
                $uploadSuccessPath = $path . date("Ymd") . "/" . $fileName;
                $result[`file_name`] = $model->file->baseName;
                $result[`file_path`] = $uploadSuccessPath;
            } else {
                //上傳失敗記錄日誌
                self::recordLog($model->errors, $field, `Upload`);
                
                return false;
            }
        } else {
            return false;
        }

驗證的model類,引數沒有寫那麼多,可以把需要的引數都加上,每個專案或者模組需要用到上傳的時候,在配置檔案params裡配置上相關的引數就可以了

<?php

namespace commonmodels;

use yiiaseModel;

/**
 * Class UploadValidate 檔案上傳驗證
 * 使用model驗證檔案上傳欄位
 * ```
 * $model = new UploadValidate($config_name);
 * ```
 *
 * @package commonmodels
 * @author  windhoney
 * @package commonmodels
 */
class UploadValidate extends Model
{
    
    /**
     * @var string 表單欄位名
     */
    public $file;
    /**
     * @var array|string 副檔名
     */
    public $extensions;
    /**
     * @var int 檔案大小 最大值  單位位元組
     */
    public $max_size = 60 * 1024 * 1024;
    /**
     * @var int 檔案大小 最小值  單位位元組
     */
    public $min_size = 1;
    /**
     * @var array|string  MIME TYPE
     */
    public $mime_type;
    /**
     * @var string 上傳失敗後返回資訊
     */
    public $message = `上傳失敗`;
    
    /**
     * UploadValidate constructor.
     *
     * @param string $config_name `@app/config/params.php` 檔案上傳驗證配置項名稱
     */
    public function __construct($config_name)
    {
        parent::__construct();
        $upload_config = Yii::$app->params[$config_name];
        $this->extensions = $upload_config[`extensions`]??``;
        $this->mime_type = $upload_config[`mime_types`]??``;
        $this->max_size = $upload_config[`max_size`]??``;
        $this->min_size = $upload_config[`min_size`]??``;
        $this->message = $upload_config[`message`]??``;
    }
    
    /**
     * @inheritdoc 驗證規則
     */
    public function rules()
    {
        $file_rule = [[`file`], `file`];
        if ($this->extensions) {
            $file_rule[`extensions`] = $this->extensions;
        }
        if ($this->mime_type) {
            $file_rule[`mimeTypes`] = $this->mime_type;
        }
        if ($this->max_size) {
            $file_rule[`maxSize`] = $this->max_size;
        }
        if ($this->min_size) {
            $file_rule[`minSize`] = $this->min_size;
        }
        if ($this->message) {
            $file_rule[`message`] = $this->message;
        }
        $rules = [$file_rule];
        
        return $rules;
    }
}

配置檔案 @app/config/params.php

<?php
return [
    `test_upload` => [
        `extensions` => [`jpg`, `png`, `jpeg`, `jpe`, `pdf`],
        `mime_types` => [`image/*`, `application/pdf`],
        `max_size` => 10 * 1024 * 1024,
        `min_size` => 1,
        `message` => `上傳失敗`,
    ]
];

使用步驟

  //例項化上傳驗證類,傳入上傳配置引數項名稱
  $model = new UploadValidate(`test_upload`);
  //上傳
  $result = CommonHelper::myUpload($model, $field, `test`);

相關文章