vue3.2使用@wangeditor/editor-for-vue实现富文本编辑器,后端使用thinkphp上传图片

发布于:2024-07-23 ⋅ 阅读:(88) ⋅ 点赞:(0)

Vue 组件代码

npm i @wangeditor/editor-for-vue
<template>
  <div style="border: 1px solid #ccc;height:600px;">
      <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
      <Editor style="height: 500px; overflow-y: hidden;" v-model="editorValueHtml" :defaultConfig="editorConfig"
        :mode="mode" @onCreated="handleCreated" />
    </div>
</template>

<script setup lang="ts">
import { ref, Ref, onMounted, onBeforeUnmount, shallowRef, reactive } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()

const mode: Ref = ref('default') // 'default' 或 'simple'

// editor HTML
const editorValueHtml = ref('<p>hello</p>')
// 工具栏配置
const toolbarConfig = {}

// 初始化配置
const editorConfig: any = {
  MENU_CONF: {}
}

editorConfig.placeholder = '请输入内容...'
editorConfig.MENU_CONF['uploadImage'] = {
  server: '上传图片接口',
  timeout: 5 * 1000, // 5s
  fieldName: 'image',
  // meta: { token: 'xxx', a: 100 },
  metaWithUrl: false, // join params to url
  headers: { Accept: 'text/x-json' },
  allowedFileTypes: ['image/*'],
  maxFileSize: 5 * 1024 * 1024, // 5M
  base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

  onBeforeUpload(file: any) {
    console.log('onBeforeUpload', file)

    return file // will upload this file
    // return false // prevent upload
  },
  onProgress(progress: any) {
    console.log('onProgress', progress)
  },
  onSuccess(file: any, res: any) {
    console.log('onSuccess', file, res)
  },
  onFailed(file: any, res: any) {
    alert(res.message)
    console.log('onFailed', file, res)
  },
  onError(file: any, err: any, res: any) {
    alert(err.message)
    console.error('onError', file, err, res)
  },
}

onMounted(() => {
  setTimeout(() => {
    editorValueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  }, 1500)
})


// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 创建实例
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例,重要!
}
</script>

thinkphp上传图片接口

<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\facade\Request;
use think\Validate;

class Upload
{
    public function uploadImage(){
        // 获取表单上传文件
        $file = Request::file('image');

        if ($file) {
            // 手动验证文件扩展名
            $validate = new Validate([
                'ext' => 'jpg,png,gif,jpeg',
            ]);

            // 获取文件名和扩展名
            $fileName = $file->getOriginalName();
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            
            // 验证文件扩展名
            if (!$validate->check(['ext' => $ext])) {
                return json(['errno' => 1, 'message' => '文件格式不正确']);
            }

            // 定义保存目录
            $saveDir = './uploads/';  // 将文件保存到 public/uploads 目录
            // 确保保存目录存在
            if (!is_dir($saveDir)) {
                mkdir($saveDir, 0777, true);
            }

            // 生成文件的唯一名称,防止文件名重复
            $uniqueFileName = uniqid() . '-' . $fileName;
            $savePath = $saveDir . $uniqueFileName;

            // 移动文件到指定目录
            if ($file->move($saveDir, $uniqueFileName)) {
                $url = Request::domain() . '/uploads/' . $uniqueFileName;

                // 返回图片 URL
                return json(['errno' => 0, 'data' => ['url' => $url]]);
            } else {
                // 上传失败获取错误信息
                return json(['errno' => 1, 'message' => $file->getError()]);
            }
        } else {
            return json(['errno' => 1, 'message' => '没有上传文件']);
        }
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到