wangeditor富文本編輯器: http://www.wangeditor.com/javascript
案例使用laravel框架php
// /routes/web.php Route::get('/test','Test\TestController@index'); // /routes/api.php Route::post('/editor/upload/picture', 'Test\TestController@editorUploadPicture'); //編輯器上傳圖片,放到api中能夠避免csrf校驗
<?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'=>[]]); } }
<!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>