YII2文件上傳驗證,簡單封裝

上傳使用FileInput插件
官方文檔 http://demos.krajee.com/widge...
也參考了 http://www.manks.top/yii2_mul...
插件參數比較多。前臺表單部分,能夠參照具體例子寫就好了。php

主要是上傳以後的處理和驗證,驗證文件的類型,大小等,我寫了一個公共方法來處理上傳html

/**
     * 文件上傳
     * ```
     *  $model = new UploadValidate($config_name);
     *  $result = CommonHelper::myUpload($model, $field, 'invoice');
     * ```
     *
     * @param  object $model \common\models\UploadValidate 驗證上傳文件
     * @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裏配置上相關的參數就能夠了yii2

<?php

namespace common\models;

use yii\base\Model;

/**
 * Class UploadValidate 文件上傳驗證
 * 使用model驗證文件上傳字段
 * ```
 * $model = new UploadValidate($config_name);
 * ```
 *
 * @package common\models
 * @author  windhoney
 * @package common\models
 */
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.phpapp

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

使用步驟yii

//實例化上傳驗證類,傳入上傳配置參數項名稱
  $model = new UploadValidate('test_upload');
  //上傳
  $result = CommonHelper::myUpload($model, $field, 'test');
相關文章
相關標籤/搜索