mg007

wangeditor富文本编辑器: http://www.wangeditor.com/

案例使用laravel框架

1、定义2个路由

// /routes/web.php
Route::get(\'/test\',\'Test\TestController@index\');

// /routes/api.php
Route::post(\'/editor/upload/picture\', \'Test\TestController@editorUploadPicture\');
//编辑器上传图片,放到api中可以避免csrf校验

2、控制器

<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index()
    {
        return view(\'index\');
    }

    //编辑器上传图片
    public function editorUploadPicture(Request $request)
    {
        $directory = $request->input(\'directory\',\'editor-upload/\');

        if(!$request->hasFile(\'picture\')){
            return json_encode([\'errno\'=>0,\'msg\'=>\'no file\',\'data\'=>[]]);
        }

        $picture = $request->file(\'picture\');

        if($picture->isValid()) {
            $extension = $picture->getClientOriginalExtension();//获得上传文件后缀
            $newName = date(\'YmdH\').\'-\' . mt_rand(1000, 9999) . \'.\' . $extension;

            $picture->move($directory, $newName);//上传文件到服务器指定目录,并重命名
            $picturePath = \'/\'.$directory . $newName; //给用户一个相对路径

            return json_encode([\'errno\'=>0,\'msg\'=>\'ok\',\'data\'=>[$picturePath]]);
        }
        return json_encode([\'errno\'=>0,\'msg\'=>\'error\',\'data\'=>[]]);
    }
}

3、视图

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script type="text/javascript" src="/js/jquery-1.7.1.min.js"></script>
    <script src="//unpkg.com/wangeditor/release/wangEditor.min.js"></script>
</head>
<body>
<div class="col-lg-10">
    <div id="ContentHtml"></div>
    <textarea id="Content" name="content" style="display: none;"></textarea>
</div>

<script type="text/javascript">
    $(function(){
        //--富文本编辑器 start
        var E = window.wangEditor;
        var editor = new E(\'#ContentHtml\');
        var $text1 = $(\'#Content\');

        editor.customConfig.uploadImgShowBase64 = true;   // 使用 base64 保存图片
        editor.customConfig.uploadImgServer = \'/api/editor/upload/picture?directory=editor-upload/\';  // 上传图片到服务器
        editor.customConfig.uploadFileName = \'picture\';

        editor.customConfig.onchange = function (html) {
            $text1.val(html);// 监控变化,同步更新到 textarea
        };
        editor.create();
        $text1.val(editor.txt.html());// 初始化 textarea 的值
        //--富文本编辑器 end
    });
</script>
</body>
</html>

4、效果

分类:

技术点:

相关文章:

  • 2021-11-08
  • 2021-10-06
  • 2022-01-01
  • 2022-01-18
  • 2021-12-29
  • 2022-01-01
  • 2021-10-20
  • 2021-06-15
猜你喜欢
  • 2021-12-09
  • 2021-11-11
  • 2021-10-08
  • 2022-01-13
  • 2021-08-30
  • 2021-04-18
  • 2021-10-01
相关资源
相似解决方案