laravel中使用WangEditor及多图上传

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:

Encore\Admin\Providers\AdminServiceProvider::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

3.2 集成富文本编辑器wangEditor

先下载前端库文件wangEditor,解压到目录public/vendor/wangEditor-3.0.9

然后新建组件类app/Admin/Extensions/WangEditor.php
关于WangEditor设置部分请阅读官方文档

formatName($this->column);

        $this->script = <<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

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

{!! old($column, $value) !!}

然后注册进laravel-admin,在app/Admin/bootstrap.php中添加以下代码:

调用:

$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

修改app\Controllers\UploadsController.php

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 . "张图片上传失败
"; $return[] = ['ResultData' => 0, 'info' => $msg, 'newFileName' => $newFileName]; } else { return response()->json(['ResultData' => 3, 'info' => '第' . $n . '张图片后缀名不合法!
' . '只支持jpeg/jpg/png/gif格式']); } } else { return response()->json(['ResultData' => 1, 'info' => '第' . $n . '张图片超过最大限制!
' . '图片最大支持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/',
    ],

预览图

  • 可以看出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两个方法

attributes['cover'] = json_encode($cover);
        }
    }

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

显示效果

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

你可能感兴趣的:(图片上传,javascript,editor,php,laravel)