【转载】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
<?php use Encore\Admin\Form; 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 App\Admin\Extensions; use Encore\Admin\Form\Field; 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 App\Admin\Extensions\WangEditor; use Encore\Admin\Form; 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
修改app\Controllers\UploadsController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; 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/', ],
预览图
- 可以看出
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 App\Models; use Illuminate\Database\Eloquent\Model; 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); } }
显示效果
原文链接 https://www.bear777.com/blog/laravel-wangeditor
github地址 https://github.com/pandoraxm/laravel-admin-wangeditor