laravel富文本编辑器使用&上传图片

简介laravel富文本编辑器使用

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>
    
    
</head>
<body>
<div class="col-lg-10">
    <div id="ContentHtml"></div>
    <textarea id="Content" name="content" style="display: none;"></textarea>
</div>


</body>
</html>


4、效果



 

文章评论

共有0条评论来说两句吧...

用户名:

验证码:

Top