laravel中使用WangEditor及多圖上傳

max_bear發表於2019-02-16

laravel中使用WangEditor及多圖上傳

1. 建立專案及安裝所需安裝包

1.1 建立專案

composer create-project laravel/laravel=5.3 blog_wangeditor --prefer-dist

1.2 建立資料庫及配置檔案

vim .env

1.3 安裝中文包

composer require "caouecs/laravel-lang:~3.0"

安裝之後將語言包移動到對應位置就好了,語言包預設位置是resources/lang

cp -a vendor/caouecs/laravel-lang/src/zh-CN resources/lang

修改config/app.php將local的值改為zh-CN

1.4 安裝laravel-admin

composer 安裝

composer require encore/laravel-admin "1.3.*"

config/app.php加入ServiceProvider:

EncoreAdminProvidersAdminServiceProvider::class

釋出資源

php artisan vendor:publish --tag=laravel-admin

安裝

php artisan admin:install

1.5 快速生成前端登入註冊模組

php artisan make:auth

執行遷移

php artisan migrate

2. 快速生成文章管理

2.1 建立遷移表

php artisan make:migration create_posts_table --create=posts

2.2 修改遷移表database/2018_01_14_191442_create_posts_table.php

    public function up()
    {
        Schema::create(`posts`, function (Blueprint $table) {
            $table->increments(`id`);
            $table->text(`title`);
            $table->text(`subtitle`);
            $table->text(`cover`);
            $table->enum(`type`, [`0`, `1`, `2`, `3`, `4`, `5`, `9`])->default(`0`);
            $table->text(`content`);
            $table->timestamps();
        });
    }

2.3 執行遷移

php artisan migrate

2.4 建立模型和控制器

模型

php artisan make:model App\Models\Post

控制器

php artisan admin:make PostController --model=App\Models\Post

2.5 新增文章後臺路由

Admin/routes.php

$router->resource(`/post`, `PostController`);

2.6 修改app/Admin/PostController.php裡面的form和grid兩個方法

    protected function grid()
    {
        return Admin::grid(Post::class, function (Grid $grid) {

            $grid->id(`ID`)->sortable();
            $grid->title(`標題`);
            $grid->subtitle(`副標題`);
            $grid->type(`型別`)->options([
                `0` => `php`,
                `1` => `laravel`,
                `2` => `javascript`,
                `3` => `python`,
                `4` => `golang`,
                `5` => `linux`,
                `9` => `other`
            ]);
             $grid->cover(`封面`)->image(`/uploads`, 100, 100);
            $grid->content(`內容`)->limit(100);
            $grid->created_at(`建立時間`);
            $grid->updated_at(`修改時間`);
        });
    }

    protected function form()
    {
        return Admin::form(Post::class, function (Form $form) {

            $form->display(`id`, `ID`);
            $form->text(`title`, `標題`);
            $form->textarea(`subtitle`, `副標題`)->rows(3);
            $form->select(`type`, `型別`)->options([
                `0` => `php`,
                `1` => `laravel`,
                `2` => `javascript`,
                `3` => `python`,
                `4` => `golang`,
                `5` => `linux`,
                `9` => `other`
            ]);
            $form->image(`cover`, `封面`);
            $form->editor(`content`, `內容`);
            $form->display(`created_at`, `建立時間`);
            $form->display(`updated_at`, `修改時間`);
        });
    }

3. 整合WangEditor編輯器

3.1 移除已有元件

修改app/Admin/bootstrap.php

<?php

use EncoreAdminForm;

Form::forget(`map`);
Form::forget(`editor`);

// or

Form::forget([`map`, `editor`]);

3.2 整合富文字編輯器wangEditor

先下載前端庫檔案wangEditor,解壓到目錄public/vendor/wangEditor-3.0.9

然後新建元件類app/Admin/Extensions/WangEditor.php
關於WangEditor設定部分請閱讀官方文件

<?php

namespace AppAdminExtensions;

use EncoreAdminFormField;

class WangEditor extends Field
{
    protected $view = `admin.wang-editor`;

    protected static $css = [
        `/vendor/wangEditor-3.0.9/release/wangEditor.min.css`,
    ];

    protected static $js = [
        `/vendor/wangEditor-3.0.9/release/wangEditor.min.js`,
    ];

    public function render()
    {
        $name = $this->formatName($this->column);

        $this->script = <<<EOT

var E = window.wangEditor
var editor = new E(`#{$this->id}`);
editor.customConfig.uploadFileName = `mypic[]`;
editor.customConfig.uploadImgHeaders = {
    `X-CSRF-TOKEN`: $(`input[name="_token"]`).val()
}
editor.customConfig.zIndex = 0;
// 上傳路徑
editor.customConfig.uploadImgServer = `/uploadFile`;
editor.customConfig.onchange = function (html) {
    $(`input[name=$name]`).val(html);
}
editor.customConfig.uploadImgHooks = {
    customInsert: function (insertImg, result, editor) {
        if (typeof(result.length) != "undefined") {
            for (var i = 0; i <= result.length - 1; i++) {
                var j = i;
                var url = result[i].newFileName;
                insertImg(url);
            }
            toastr.success(result[j][`info`]);
        }

        switch (result[`ResultData`]) {
            case 6:
                toastr.error("最多可以上傳4張圖片");
                break;
            case 5:
                toastr.error("請選擇一個檔案");
                break;
            case 4:
                toastr.error("上傳失敗");
                break;
            case 3:
                toastr.error(result[`info`]);
                break;
            case 2:
                toastr.error("檔案型別不合法");
                break;
            case 1:
                toastr.error(result[`info`]);
                break;
        }
    }
}
editor.create();

// var editor = new wangEditor(`{$this->id}`);
//     editor.create();

EOT;
        return parent::render();

    }
}

新建檢視檔案resources/views/admin/wang-editor.blade.php

<div class="form-group {!! !$errors->has($label) ?: `has-error` !!}">

    <label for="{{$id}}" class="col-sm-2 control-label">{{$label}}</label>

    <div class="col-sm-{{$width[`field`]}}">

        @include(`admin::form.error`)

        <div id="{{$id}}" style="width: 100%; height: 100%;">
            <p>{!! old($column, $value) !!}</p>
        </div>

        <input type="hidden" name="{{$name}}" value="{{ old($column, $value) }}" />

    </div>
</div>

然後註冊進laravel-admin,在app/Admin/bootstrap.php中新增以下程式碼:

<?php

use AppAdminExtensionsWangEditor;
use EncoreAdminForm;

Form::extend(`editor`, WangEditor::class);

呼叫:

$form->editor(`body`);

3.3 完成WangEditor圖片上傳

3.3.1 建立上傳路由routes/web.php

Route::post(`/uploadFile`, `UploadsController@uploadImg`);

3.3.2 建立上傳檔案控制器UploadsController

php artisan make:controller UploadsController

修改appControllersUploadsController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class UploadsController extends Controller
{
    public function uploadImg(Request $request)
    {
        $file = $request->file("mypic");
        // dd($file);
        if (!empty($file)) {
            foreach ($file as $key => $value) {
                $len = $key;
            }
            if ($len > 25) {
                return response()->json([`ResultData` => 6, `info` => `最多可以上傳25張圖片`]);
            }
            $m = 0;
            $k = 0;
            for ($i = 0; $i <= $len; $i++) {
                // $n 表示第幾張圖片
                $n = $i + 1;
                if ($file[$i]->isValid()) {
                    if (in_array(strtolower($file[$i]->extension()), [`jpeg`, `jpg`, `gif`, `gpeg`, `png`])) {
                        $picname = $file[$i]->getClientOriginalName();//獲取上傳原檔名
                        $ext = $file[$i]->getClientOriginalExtension();//獲取上傳檔案的字尾名
                        // 重新命名
                        $filename = time() . str_random(6) . "." . $ext;
                        if ($file[$i]->move("uploads/images", $filename)) {
                            $newFileName = `/` . "uploads/images" . `/` . $filename;
                            $m = $m + 1;
                            // return response()->json([`ResultData` => 0, `info` => `上傳成功`, `newFileName` => $newFileName ]);

                        } else {
                            $k = $k + 1;
                            // return response()->json([`ResultData` => 4, `info` => `上傳失敗`]);
                        }
                        $msg = $m . "張圖片上傳成功 " . $k . "張圖片上傳失敗<br>";
                        $return[] = [`ResultData` => 0, `info` => $msg, `newFileName` => $newFileName];
                    } else {
                        return response()->json([`ResultData` => 3, `info` => `第` . $n . `張圖片字尾名不合法!<br/>` . `只支援jpeg/jpg/png/gif格式`]);
                    }
                } else {
                    return response()->json([`ResultData` => 1, `info` => `第` . $n . `張圖片超過最大限制!<br/>` . `圖片最大支援2M`]);
                }
            }

        } else {
            return response()->json([`ResultData` => 5, `info` => `請選擇檔案`]);
        }
        return $return;
    }
}

3.3.3 修改config/admin.php upload裡面的host

    `upload`  => [

        `disk` => `admin`,

        `directory`  => [
            `image`  => `image`,
            `file`   => `file`,
        ],
        // 將upload改為uploads
        `host` => `http://localhost:8000/uploads/`,
    ],

預覽圖
圖1

  • 可以看出WangEditor上傳多圖是沒有問題的

可是有時候我們想給文章配多個封面圖怎麼辦?
下面我們就來完成,laravel-admin的多圖上傳。

4. laravel-admin 多圖上傳

4.1 修改app/Admin/PostController裡面的form()方法

$form->image(`cover`, `封面`);
修改為$form->multipleImage(`cover`, `封面`);

4.2 建立圖片修改器

laravel修改器使用說明,請閱讀相關說明文件
app/Models/Post.php裡增加setCoverAttribute()
setCoverAttribute兩個方法

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Post extends Model
{
    public function setCoverAttribute($cover)
    {
        if (is_array($cover)) {
            $this->attributes[`cover`] = json_encode($cover);
        }
    }

    public function getCoverAttribute($cover)
    {
        return json_decode($cover, true);
    }
}

顯示效果
圖2

原文地址https://www.bear777.com/blog/laravel-wangeditor
github地址https://github.com/pandoraxm/laravel-admin-wangeditor

相關文章