目录
环境交代
本文章测试环境及官方网址如下:
Laravel版本:8.40
php版本:PHP 7.3.14
WangEditor:wangeditor4.7.6
Vue:2.6.10
WangEditor官方网址:https://www.wangeditor.com/
Laravel官方网站:https://laravel.com/
Laravel中文网站:https://www.golaravel.com/
Vue官方网站:https://cn.vuejs.org/
前端代码
1、使用npm命令执行安装WangEditor
npm i wangeditor --save
2、新建一个vue页面,内容如下
<template>
<div class="content">
<div id="editor"></div>
<button style="margin-top:30px;" @click="save">保存数据</button>
</div>
</template>
<style scoped>
.content{margin: 30px;}
#editor{width: 800px;}
</style>
<script>
import E from 'wangeditor'
export default {
data(){
return {
editor:undefined
}
},
mounted(){
this.editor = new E('#editor')
this.editor.config.height = 500 //设置编辑器高度
this.editor.config.menus = ['image'] //自定义编辑器显示的菜单
this.editor.config.uploadImgServer = '/dev-api/uploadImage/' //图片上传路径
this.editor.config.uploadImgMaxLength = 9 //设置一次最多上传9张图片,默认100张
this.editor.create()
},
methods:{
save(){
console.log(this.editor.txt.html()) //输出编辑器生成的html
}
}
}
</script>
后端代码
1、laravel 新建一个路由
Route::post('uploadImage',[UploadImageController::class,"index"]);
2、 新建一个图片上传控制器
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class UploadImageController extends Controller
{
//图片上传
//此示例未校验图片是否上传成功,
public function index(Request $request)
{
$files = $request->allFiles();
$data = array();
$imgHost = "http://127.0.0.1:8000";
foreach($files as $file){
$url = $file->storePublicly('public/editor');
$showPic = Storage::url($url);
$item = array("url"=>$imgHost.$showPic,"alt"=>"","href"=>$imgHost.$showPic);
array_push($data,$item);
}
return response(array(
"errno"=>0,
"data"=>$data
));
}
}
注意事项
注意:要先创建软链,如果项目没有执行php artisan Storage:link则有可能图片无法显示
php artisan Storage:link
最终显示效果
Html显示为