Laravel

Laravel中使用wangEditor

2017-03-01  本文已影响2167人  ONEDAYLOG

wangEditor是一个优秀的国产的轻量级富文本编辑器(虽然本人还是喜欢MarkDown,但是不是任何人都喜欢MarkDown这样的编写方式的),wangEditor和百度的UEditor相比,确实是要轻量很多,UEditor太过于臃肿而且编辑用起来很难做到格式的一个统一性。

本人现在在使用laravel-admin这个后台的框架,感觉用起来还比较轻量级,中文文档充足。

截图

创建一个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扩展

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:直接看这里

截图

后续使用后的更新

使用上面的上传图片感觉非常的不爽,图片处理太弱了,都无法压缩、水印、调整大小等等
推荐使用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();
    }

}

上一篇下一篇

猜你喜欢

热点阅读