Laravel中使用wangEditor

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();
    }

}


作者:ONEDAYLOG
链接:https://www.jianshu.com/p/8cf60e0fc47e
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个使用 Redis 做缓存的 Laravel 示例: 1. 安装 Redis 在 Laravel 使用 Redis 需要先安装 Redis 扩展和 Predis 客户端库。可以通过以下命令安装: ```bash $ sudo apt-get install redis-server $ composer require predis/predis ``` 2. 配置 Redis 在 Laravel 配置 Redis 需要在 `config/database.php` 文件添加 Redis 的连接信息。可以参考以下示例: ```php 'redis' => [ 'client' => 'predis', 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ``` 3. 使用 Redis 缓存 在 Laravel 使用 Redis 缓存可以使用 `Cache` Facade。可以参考以下示例: ```php use Illuminate\Support\Facades\Cache; // 缓存数据 Cache::put('key', 'value', $minutes); // 获取缓存数据 $value = Cache::get('key'); // 删除缓存数据 Cache::forget('key'); ``` 4. 使用 Redis 做 Session 存储 在 Laravel 使用 Redis 做 Session 存储也很简单,只需要在 `config/session.php` 文件修改 `driver` 为 `redis`,并配置 Redis 连接信息即可。可以参考以下示例: ```php 'driver' => env('SESSION_DRIVER', 'file'), 'connection' => env('SESSION_CONNECTION', 'default'), 'table' => 'sessions', 'store' => env('SESSION_STORE', null), 'lottery' => [2, 100], 'lifetime' => 120, 'expire_on_close' => false, 'encrypt' => false, 'files' => storage_path('framework/sessions'), 'cookie' => env( 'SESSION_COOKIE', Str::slug(env('APP_NAME', 'laravel'), '_').'_session' ), 'path' => '/', 'domain' => env('SESSION_DOMAIN', null), 'secure' => env('SESSION_SECURE_COOKIE'), 'http_only' => true, 'same_site' => 'lax', ``` 以上就是一个简单的 Laravel 使用 Redis 的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值