Laravel+WangEditor+Vue图片上传

目录

环境交代

前端代码

后端代码

注意事项

最终显示效果


环境交代

本文章测试环境及官方网址如下:

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显示为

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值