Yii2.0-advanced-8—圖片上傳之webuploader的使用

yii2 -圖片上傳之webUploader的使用

1、安裝

推薦使用composer進行安裝

$ composer require bailangzhan/yii2-webuploader dev-master

如果composer安裝有問題還可以手動安裝,方法如下:

( github地址 : https://github.com/wlzx120/yii2-webuploder.git )

1、 將整個文件夾複製到vendor目錄下:/vendor/yii2-webuploader

2、 修改配置文件 extension 給webuploader設置別名

配置文件路徑:/vendor/yiisoft/extensions.php

在文件array最後加入:

'yii2-webuploader'=>
array(
    
'name' =>'yii2-webuploader',
    
'version' => '9999999-dev',
    
'alias' =>
    
array (
      
'@manks' => $vendorDir.'/yii2-webuploader',
    ),
),

然後就可以配置使用了;

2、配置

params.php或者params-local.php內增加webuploaderdomain配置項

/* 圖片上傳插件webuploader + */
    'webuploader' => [
        // 後端處理圖片的action,value是相對的地址
        'uploadUrl' => 'blog/upload',
        // 多文件分隔符
        'delimiter' => ',',
        // 基本配置
        'baseConfig' => [
            'defaultImage' => 'http://img1.imgtn.bdimg.com/it/u=2056478505,162569476&fm=26&gp=0.jpg',
            'disableGlobalDnd' => true,
            'accept' => [
                'title' => 'Images',
                'extensions' => 'gif,jpg,jpeg,bmp,png',
                'mimeTypes' => 'image/*',
            ],
            'pick' => [
                'multiple' => false,
            ],
        ],
    ],
    'domain' => 'http://admin.yii2test.com',       // 訪問圖片的域名拼接
    'imageUploadRelativePath' => './uploads/images/', // 圖片默認上傳的目錄
    'imageUploadSuccessPath' => '/uploads/images/', // 圖片上傳成功後,路徑前綴
    /* 圖片上傳插件webuploader - */

webuploader['baseConfig'] 參考 webuploader官方的參數說明

3、使用

view中:

單圖

<?php
        echo $form->field($model, 'image')->widget('manks\FileInput', []
    ); ?>

多圖

<?php
        echo $form->field($model, 'image')->widget('manks\FileInput', [
            //多個圖片上傳需添加以下參數
            'clientOptions' => [
                'pick' => [
                    'multiple' => true,
                ],
            ],
    ]); ?>

控制器controller的地址可以在params.php或者params-local.php中配置Yii::$app->params['webuploader']['uploadUrl'],也可以在clientOptions中配置server項。控制器需要返回的數據格式如下

// 錯誤時
{"code": 1, "msg": "error"}
// 正確時,其中 attachment 指的是保存在數據庫中的路徑,url 是該圖片在web可訪問的地址
{"code": 0, "url": "http://domain/圖片地址", "attachment": "圖片地址"}

clientOptions同樣參考 webuploader官方的參數說明

注意:如果是修改的多圖片操作,務必保證 $model->file = 'src1,src2,src3,...'; 或者 $model->file = ['src1', 'src2'. 'src3', ...];

controller中:

首先假設webuploader是按照前面所配置的,控制器就是blog/upload,先看下BlogController的實現

use common\components\Upload;
use yii\web\Response;

    //webUploader上傳
    public function actionUpload()
    {
        try {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $model = new Upload();
            $info = $model->upImage();
            if ($info && is_array($info)) {
                return $info;
            } else {
                return ['code' => 1, 'msg' => 'error'];
            }
        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }

當然,你的common/components目錄下還沒有Upload.php,其代碼參考如下

<?php
namespace common\components;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\base\Exception;
use yii\helpers\FileHelper;
/**
 * 文件上傳處理
 */
class Upload extends Model
{
    public $file;
    private $_appendRules;
    public function init ()
    {
        parent::init();
        $extensions = Yii::$app->params['webuploader']['baseConfig']['accept']['extensions'];
        $this->_appendRules = [
            [['file'], 'file', 'extensions' => $extensions],
        ];
    }
    public function rules()
    {
        $baseRules = [];
        return array_merge($baseRules, $this->_appendRules);
    }
    /**
     *
     */
    public function upImage ()
    {
        $model = new static;
        $model->file = UploadedFile::getInstanceByName('file');
        if (!$model->file) {
            return false;
        }
        $relativePath = $successPath = '';
        if ($model->validate()) {
            $relativePath = Yii::$app->params['imageUploadRelativePath'];
            $successPath = Yii::$app->params['imageUploadSuccessPath'];
            $fileName = $model->file->baseName . '.' . $model->file->extension;
            if (!is_dir($relativePath)) {
                FileHelper::createDirectory($relativePath);
            }
            $model->file->saveAs($relativePath . $fileName);
            return [
                'code' => 0,
                'url' => Yii::$app->params['domain'] . $successPath . $fileName,
                'attachment' => $successPath . $fileName
            ];
        } else {
            $errors = $model->errors;
            return [
                'code' => 1,
                'msg' => current($errors)[0]
            ];
        }
    }
}

對於原form對應的AR模型來看,我們假設filefile2字段分別是單圖和多圖字段,那麼在數據庫保存的時候,$model->file="src";$model->file2="src1,src2,src3,...";

AR模型對應的rules我們可以這樣寫

public function rules()
{
    return [
        [['file', 'file2'], 'required'],
        [['file', 'file2'], 'safe'],
        [['file'], 'string', 'max' => 255],
    ];
}

即保證filefile2必填且file限制255個字符。

此外,數據入庫之前,你還需要對file2進行拆分處理

is_array($this->file2) && $this->file2 && $this->file2 = implode(',', $this->file2);

 

完結

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章