Laravel中使用wangEditor

weixin_33749242發表於2017-03-01

wangEditor是一個優秀的國產的輕量級富文字編輯器(雖然本人還是喜歡MarkDown,但是不是任何人都喜歡MarkDown這樣的編寫方式的),wangEditor和百度的UEditor相比,確實是要輕量很多,UEditor太過於臃腫而且編輯用起來很難做到格式的一個統一性。

本人現在在使用laravel-admin這個後臺的框架,感覺用起來還比較輕量級,中文文件充足。

4445477-5885929c90ca40fb.png
截圖

建立一個Field的擴充套件

<?php
namespace App\Admin\Extensions;

use Encore\Admin\Form\Field;

class WangEditor extends Field
{
    protected $view = 'admin.wangeditor';

    protected static $css = [
        '/packages/admin/wangEditor/dist/css/wangEditor.min.css',
    ];

    protected static $js = [
        '/packages/admin/wangEditor/dist/js/wangEditor.js',
    ];

    public function render()
    {
        $editor_id = $this->id;
        $z_index = 999999;

        $printLog = config('wang-editor.printLog', 'true');
        $uploadImgUrl = config('wang-editor.uploadImgUrl', '/admin/upload/uploadImg');
        $mapAk = config('wang-editor.mapAk', 'TVhjYjq1ICT2qqL5LdS8mwas');
        $pasteFilter = config('wang-editor.pasteFilter', 'false');
        $pasteText = 'true';
        if ($pasteFilter == 'true') {
            $pasteText = config('wang-editor.pasteText', 'true');
        }
        $token = csrf_token();

        $this->script = <<<EOT

            var menus = [
                'source',
                '|',
                'bold',
                'underline',
                'italic',
                'strikethrough',
                'eraser',
                'forecolor',
                'bgcolor',
                '|',
                'quote',
                'fontfamily',
                'fontsize',
                'head',
                'unorderlist',
                'orderlist',
                'alignleft',
                'aligncenter',
                'alignright',
                '|',
                'link',
                'unlink',
                'table',
                'emotion',
                '|',
                'img',
                'video',
                // 'location',
                'insertcode',
                '|',
                'undo',
                'redo',
                'fullscreen'
            ];
            wangEditor.config.printLog = {$printLog};
            var _{$editor_id} = new wangEditor('{$editor_id}');
            _{$editor_id}.config.uploadImgUrl = "{$uploadImgUrl}";
            _{$editor_id}.config.uploadParams = {
                    token : '{$token}'
            };
            _{$editor_id}.config.mapAk = '{$mapAk}';
            _{$editor_id}.config.zindex = {$z_index};
            var _pasteFilter = {$pasteFilter};
            _{$editor_id}.config.pasteFilter = _pasteFilter;
            if (_pasteFilter == true) {
                _{$editor_id}.config.pasteText = {$pasteText};
            }
            _{$editor_id}.config.uploadImgFileName = 'wang-editor-image-file';
            _{$editor_id}.create();
EOT;
        return parent::render();

    }
}

建立對應的blade view

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

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

    <div class="col-sm-6">

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

        <textarea style="height:400px;max-height:500px;display: none" cols="5" class="form-control" id="{{$id}}" name="{{$name}}" placeholder="{{ $placeholder }}" {!! $attributes !!} >{{ old($column, $value) }}</textarea>

        @include('admin::form.help-block')

    </div>
</div>

bootstrap.php中註冊擴充套件

Form::extend('wangeditor', WangEditor::class);

呼叫這個wangeditor擴充套件

4445477-f0e80b52783164f9.png
QQ截圖20170301131426.png

這個時候基本你就可以使用wangeditor編輯器,但是無法上傳圖片

public function postUploadPicture(Request $request)
    {
        if ($request->hasFile('wang-editor-image-file')) {
            //
            $file = $request->file('wang-editor-image-file');
            $data = $request->all();
            $rules = [
                'wang-editor-image-file'    => 'max:5120',
            ];
            $messages = [
                'wang-editor-image-file.max'    => '檔案過大,檔案大小不得超出5MB',
            ];


            $validator = Validator($data, $rules, $messages);
//            $validator = $this->validate($data, $rules, $messages);


            $res = 'error|失敗原因為:非法傳參';
            if ($validator->passes()) {
                $realPath = $file->getRealPath();
                $destPath = 'uploads/content/';
                $savePath = $destPath.''.date('Ymd', time());
                is_dir($savePath) || mkdir($savePath);  //如果不存在則建立目錄
                $name = $file->getClientOriginalName();
                $ext = $file->getClientOriginalExtension();
                $check_ext = in_array($ext, ['gif', 'jpg', 'jpeg', 'png'], true);
                if ($check_ext) {
                    $uniqid = uniqid().'_'.date('s');
                    $oFile = $uniqid.'o.'.$ext;
                    $fullfilename = '/'.$savePath.'/'.$oFile;  //原始完整路徑
                    if ($file->isValid()) {
                        $uploadSuccess = $file->move($savePath, $oFile);  //移動檔案
                        $oFilePath = $savePath.'/'.$oFile;
                        $res = $fullfilename;
                    } else {
                        $res = 'error|失敗原因為:檔案校驗失敗';
                    }
                } else {
                    $res = 'error|失敗原因為:檔案型別不允許,請上傳常規的圖片(gif、jpg、jpeg與png)檔案';
                }
            } else {
                $res = 'error|'.$validator->messages()->first();
            }
        }
        return $res;
    }

路由註冊一下和擴充套件中配置的路徑統一就可以使用上傳圖片了,不使用Laravel-admin框架的可以直接使用wangEditor:直接看這裡

4445477-d5b4c08c51af6f0b.png
截圖

後續使用後的更新

使用上面的上傳圖片感覺非常的不爽,圖片處理太弱了,都無法壓縮、水印、調整大小等等
推薦使用image.intervention處理圖片

<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Str;
use Intervention\Image\ImageManagerStatic;



class UpLoadController extends Controller
{
    use ModelForm;

    /**
     * Storage instance.
     *
     * @var string
     */
    protected $storage = '';
    protected $preUrl = '';

    protected $useUniqueName = false;

    /**
     * File name.
     *
     * @var null
     */
    protected $name = null;

    /**
     * Upload directory.
     *
     * @var string
     */
    protected $directory = '';

    /**
     * 針對editor.md所寫的圖片上傳控制器
     *
     * @param  Request $requst
     * @return Response
     */
    public function postUploadPicture(Request $request)
    {
        if ($request->hasFile('wang-editor-image-file')) {
            //
            $file = $request->file('wang-editor-image-file');
            $data = $request->all();
            $rules = [
                'wang-editor-image-file'    => 'max:5120',
            ];
            $messages = [
                'wang-editor-image-file.max'    => '檔案過大,檔案大小不得超出5MB',
            ];
            
            $validator = Validator($data, $rules, $messages);
//            $validator = $this->validate($data, $rules, $messages);

            $res = 'error|失敗原因為:非法傳參';
            if ($validator->passes()) {
                $realPath = $file->getRealPath();
                $destPath = 'uploads/content/';
                $savePath = $destPath.''.date('Y', time());
                is_dir($savePath) || mkdir($savePath);  //如果不存在則建立年目錄
                $savePath = $savePath.'/'.date('md', time());
                is_dir($savePath) || mkdir($savePath);  //如果不存在則建立月日目錄
                $name = $file->getClientOriginalName();
                $ext = $file->getClientOriginalExtension();
                $check_ext = in_array($ext, ['gif', 'jpg', 'jpeg', 'png'], true);
                if ($check_ext) {
                    $uniqid = uniqid().'_'.date('s');
                    $oFile = $uniqid.'o.'.$ext;
                    $fullfilename = '/'.$savePath.'/'.$oFile;  //原始完整路徑
                    if ($file->isValid()) {
                        $uploadSuccess = $file->move($savePath, $oFile);  //移動檔案
                        $oFilePath = $savePath.'/'.$oFile;
                        $res = $fullfilename;
                    } else {
                        $res = 'error|失敗原因為:檔案校驗失敗';
                    }
                } else {
                    $res = 'error|失敗原因為:檔案型別不允許,請上傳常規的圖片(gif、jpg、jpeg與png)檔案';
                }
            } else {
                $res = 'error|'.$validator->messages()->first();
            }
        }
        return $res;
    }

    public function postUploadImg(Request $request){
        if ($request->hasFile('wang-editor-image-file')) {
            //
            $file = $request->file('wang-editor-image-file');
            $data = $request->all();
            $rules = [
                'wang-editor-image-file'    => 'max:5120',
            ];
            $messages = [
                'wang-editor-image-file.max'    => '檔案過大,檔案大小不得超出5MB',
            ];

            $validator = Validator($data, $rules, $messages);
//            $validator = $this->validate($data, $rules, $messages);

            $res = 'error|失敗原因為:非法傳參';
            if ($validator->passes()) {


                $ext = $file->getClientOriginalExtension();
                $check_ext = in_array($ext, ['gif', 'jpg', 'jpeg', 'png'], true);
                if ($check_ext) {

                    $this->disk(config('admin.upload.disk'));

                    $this->directory = 'content/'.date('Y', time()).'/'.date('md', time())."/";
                    $this->name = $this->getStoreName($file);

                    $this->renameIfExists($file);

                    $target = $this->directory.$this->name;

                    $this->storage->put($target, file_get_contents($file->getRealPath()));
                    $this->storage->makeDirectory($this->directory.'/s300/');

                    $localPath = $this->storage->getDriver()->getAdapter()-> getPathPrefix();

                    //--------------寬度過大-------------------
                    $image = ImageManagerStatic::make($localPath.$target);
                    if($image->width()>600){
                        $image->resize(600, null, function ($constraint) {
                            $constraint->aspectRatio();
                        });
                    }

                    //--------------新增水印-------------------
                    $image->insert(public_path('/img/logo.png'), 'bottom-right', 15, 10);
                    $namearr = explode('.', $this->name);
                    $image->save($localPath.$this->directory.$namearr[0].'_logo.'.$namearr[1]);

                    //-------------縮圖----------------------
                    if($image->width()>$image->height()){
                        $image->resize(300, null, function ($constraint) {
                            $constraint->aspectRatio();
                        });

                    }else{
                        $image->resize(null, 300, function ($constraint) {
                            $constraint->aspectRatio();
                        });
                    }

                    $image->save($localPath.$this->directory.'/s300/'.$namearr[0].'_logo.'.$namearr[1]);


                    if ($file->isValid()) {
//                        $res = $this->objectUrl($target);
                        $res = $this->objectUrl($this->directory.$namearr[0].'_logo.'.$namearr[1]);
                    } else {
                        $res = 'error|失敗原因為:檔案校驗失敗';
                    }

                } else {
                    $res = 'error|失敗原因為:檔案型別不允許,請上傳常規的圖片(gif、jpg、jpeg與png)檔案';
                }
            } else {
                $res = 'error|'.$validator->messages()->first();
            }
        }
        return $res;
    }

    public function disk($disk)
    {
        $this->storage = Storage::disk($disk);

        return $this;
    }

    public function renameIfExists(UploadedFile $file)
    {
        if ($this->storage->exists("$this->directory/$this->name")) {
            $this->name = $this->generateUniqueName($file);
        }
    }

    /**
     * Get store name of upload file.
     *
     * @param UploadedFile $file
     *
     * @return string
     */
    protected function getStoreName(UploadedFile $file)
    {
        if ($this->useUniqueName) {
            return $this->generateUniqueName($file);
        }

        if (is_callable($this->name)) {
            $callback = $this->name->bindTo($this);

            return call_user_func($callback, $file);
        }

        if (is_string($this->name)) {
            return $this->name;
        }

        return $file->getClientOriginalName();
    }


    public function objectUrl($path)
    {

        if (Str::startsWith($path, ['http://', 'https://'])) {
            return $path;
        }

        if($this->preUrl == ''){
            $url = config('admin.upload.host');
        }else{
            if(count(explode($this->preUrl,$path))>1){
                $url = config('admin.upload.host');
            }else{
                $url = config('admin.upload.host').$this->preUrl;
            }

        }

        return rtrim($url, '/').'/'.trim($path, '/');
    }

    protected function generateUniqueName(UploadedFile $file)
    {
        return md5(uniqid()).'.'.$file->guessExtension();
    }

}

相關文章