wangEditor自定义一个图片上传

本文介绍了wangEditor在不同网络环境下实现图片上传的三种方法:直接将图片转换为base64编码存储、通过自建接口服务器存储图片以及利用阿里云等第三方服务存储图片。每种方法都提供了详细的前端实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

wangEditor上给了几种上传图片的方式,从简单到困难:【这边只给出前端代码】

(1)上传图片的base64(可以用作练习)

(2)自己配置接口服务器存图片(需求只能连接内网情况)

(3)上传到阿里云或者其他服务器(需求可以连接外网情况)

一、上传图片的base64

这种方法会把base64存入数据库,图片小还可以,稍微大一点(10M以上),数据库就存不上了,所以只能练习使用。

源码:

<template lang="html">
  <div>
    <div ref="editor1"></div>
  </div>
</template>

<script>
//引入
import wangEditor from 'wangeditor'
import {request} from "../../network/request";
export default {
  name: 'editoritem',
  props:{
    element:{},
  },
  data() {
    return {
      //这个为富文本编辑器
      editor: null,
      //这个为富文本的内容
      editorData: '',
      haven:1
    }
  },
  beforeCreate() {
      const editor = new wangEditor(this.$refs.editor1)
      editor.config.uploadImgShowBase64 = true  // 转64方法,富文本中存入的是base64
      editor.config.onchange = (newHtml) => {
        this.editorData = newHtml
        this.$store.state.richtext = this.editorData
      }

      // 创建编辑器

      editor.create()
      this.editor = editor
    }
  },
  beforeDestroy() {
    vue需要的 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy()
    this.editor = null
  },
}
</script>
<style scoped>
</style>

过程:

 看这里图片的src为base64

 数据库中存入了base64

 注意要用Longblob,否者可能图片太大存不进数据库

 上传请求就是普通的post封装后的请求

request({
            url:'/efile/addEFile.dao',
            data:{
              nId:0,
              fileName:this.file.fileName,
              filePath:this.$store.state.richtext
            },
          }).then(res => {
            console.log(res);
            if (res.data.code == 200){
              this.$message('上传成功')
            }else {
              this.$message('上传失败')
            }
          }).catch(err => {
            this.$message('请求或网络异常')
          })
import axios from "axios"

export function request(config){
  const require = axios.create({
    method:config.method || 'post',
    baseURL:'/api/ebook/lan',
    timeout:10000,
    headers:config.method ||{'Content-Type': 'application/json;charset=utf-8'},
    data:config.data,
    withCredentials:true
  })

  return require(config)
}


封装完成的模板在这:(106条消息) vue项目模板.zip-Javascript文档类资源-优快云文库https://download.youkuaiyun.com/download/progrmmmm/43079878

         这种方法用作练习,因为没有人会把图片直接存进数据库里,一般存的都是数据库中存储这张图片的路径,服务器中存储文件。

二、自己配置接口服务器存图片(需求只能连接内网情况)

        有的需求是只有内网电脑不能连接外网的,所以就不能用阿里的服务器,只能存在本地服务器中,也就是硬盘中。

        我在这里将wangeditor封装成了组件,上面那个也封装成了组件但是就不细说了,因为上面那个不常用,这里简单说一下思路:点击按钮创建富文本,上传成功或者点击取消后销毁富文本【wangeditor用在vue上时一定要注意销毁和创建】详细的注释都在代码段中。

父组件:

<template>
  <div>
    <button type="text" @click="addClick" class="addBtn">添加</button>
    <el-dialog title="数据添加" :visible.sync="dialogFormVisible" width="600px" @closed="boom" :close-on-click-modal="false">
      <el-form :model="nodeName" ref="nodeName">
        <el-form-item  prop="fileName" label="文件名:" :label-width="formLabelWidth">
          <el-input type="fileName" autocomplete="off" placeholder="请输入" v-model="file.fileName"></el-input>
        </el-form-item>
        <el-form-item>
          <wang-enduit ref="editor"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addFileBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {request} from "../../../network/request";//封装的axios.create请求上面的连接是模板
import wangEnduit from '../../wangEnduit/index'//富文本子组件


export default {
  name: "dataAdd",
  components:{
    //注册组件
    wangEnduit
  },
  data(){
    return{
      dialogFormVisible:false,
      formLabelWidth: '120px',
      // file:[],
      nodeName:'',
      file:{
        fileName:'',
        filePath:''
      }
    }
  },
  methods:{
    boom(){
      this.$refs.editor.editors()//点击事件创建富文本
    },
    cancel(){
      this.dialogFormVisible = false
      // this.fileName = ''
      this.nodeName.name = ''
    },//用于上传内容后清空内容的方法
    addFileBtn(){
      if(this.file.fileName.length === 0){
        this.$message('请输入文件名')
      }else {
        this.dialogFormVisible = false
        request({
          url:'/efile/addEFile.dao',//存储富文本的接口
          data:{
            nId:0,
            fileName:this.file.fileName,
            filePath:this.$store.state.richtext
          },
        }).then(res => {
          console.log(res);
        }).catch(err => {
          this.$message('请求或网络异常')
        })
      }
    },
    addClick(){
      this.dialogFormVisible = true
      setTimeout(() => {//需要在创建富文本之前创建组件,所以延时一下,先让组件创建成功再创建富文本
        this.$refs.editor.creat()
      },100)
    }
  }
}
</script>

<style scoped>
.addBtn{
  width: 80px;
  height: 30px;
  background-color:#7EC0EE;
  border-radius: 0;
  border-width: 0;
  color: #FFFFFF;
  font-size: 12px;
  margin: 15px 0 15px 30px;
}
.upload{
  width: 400px;
  height: 90px;
  border: solid 1px #EBEBEB;
}
.uploadFile{
  width: 400px;
  height: 90px;
  opacity: 0;
}
.fileNameShow{
  position: absolute;
  top: 5px;
  left: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width:350px;
}
</style>

富文本组件[关键看这里,上面只是把已经存到服务器的图片路径录入数据库而已]:

<template lang="html">
  <div>
    <div ref="editor1"></div>
  </div>
</template>

<script>
//引入
import wangEditor from 'wangeditor'
import {request} from "../../network/request";

export default {
  name: 'editoritem',
  props:{
    element:{},
  },
  data() {
    return {
      //这个为富文本编辑器
      editor: null,
      //这个为富文本的内容
      editorData: '',
      haven:1
    }
  },
  beforeCreate() {

  },
  methods:{
    creat(){
      console.log("创建")
      //判断哪个id或者class的div为富文本编辑器
      const editor = new wangEditor(this.$refs.editor1)
      editor.config.uploadImgShowBase64 = true  // 转64
      editor.config.uploadImgServer = 'http://localhost:8020/ebook/lan/eimg/addEImg.dao'  // 图片要存的服务器接口
      editor.config.showLinkImg = false//禁止上传网络图片
      editor.config.customUploadImg =  (resultFiles, insertImgFn) => {
        let formData = new FormData()
        formData.append('files', resultFiles[0])//把除了图片也要上传的数据放入formdata
        formData.append('nId',0)
        request({
          method: 'post',//上传方法
          url: '/eimg/addEImg.dao',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData
        }).then(res => {
          console.log(res)
          if (res.data.code === 200) {
            insertImgFn(res.data.data)//让上传上去的图片展示在富文本中
          }
        })
      }
      //菜单,包括顺序
      editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',

        'justify',
        // 'quote',
        // 'emoticon',
        'image',
        // 'video',
        // 'table',
        // 'code',
        'splitLine',
        'undo',
        'redo',
      ]


      // 配置 onchange 回调函数,将数据同步到 vue 中
      editor.config.onchange = (newHtml) => {
        this.editorData = newHtml
      }

      // 创建编辑器

      editor.create()
      this.editor = editor
    },
    editors(){
      this.editor.destroy()//销毁组件
      this.editor = null
      console.log('销毁')
    }
  },
}
</script>
<style scoped>
</style>

axios封装:

import axios from "axios"

export function request(config){
  const require = axios.create({
    method:config.method || 'post',
    baseURL:'/api/ebook/lan',//换你自己的,可能也有跨域问题,看我主页的跨域怎么改
    timeout:10000,
    headers:config.method ||{'Content-Type': 'application/json;charset=utf-8'},
    data:config.data,
    withCredentials:true
  })

  return require(config)
}


样式:

 结果:

存储富文本:

存储路径:

 因为前后端代码不一样,所以在你的环境不一定能成功,关键是看好方法自己封装。

三、上传到阿里云或者其他服务器(需求可以连接外网情况)

        (1)上传自己的后端代码给阿里云,然后存储图片。

        (2)直接上传到阿里云的oos。

        这两点交给后端就行了,前端也就换个接口就行了。

阿里云oss图片服务器-阿里云oss图片服务器文档介绍内容-阿里云 (aliyun.com)

### WangEditor 中实现自定义图片上传 为了在 WangEditor 中实现自定义图片上传功能,可以按照以下方式操作: #### 安装依赖包 首先需要安装 `@wangeditor/editor` 和 `@wangeditor/editor-for-vue` 这两个核心库[^3]。 对于 Vue 项目而言,推荐使用如下命令进行安装: ```bash yarn add @wangeditor/editor yarn add @wangeditor/editor-for-vue@next ``` 或者也可以通过 npm 来完成相同的操作: ```bash npm install @wangeditor/editor --save npm install @wangeditor/editor-for-vue@next --save ``` #### 创建并配置编辑器实例 创建一个新的 Vue 组件用于承载编辑器,并初始化它。在此过程中需引入必要的模块并设置好初始状态。 ```javascript import { onBeforeUnmount, ref, shallowRef, watchEffect } from 'vue' import { Editor, Toolbar } from '@wangeditor/editor-for-vue' export default { components: { Editor, Toolbar }, setup() { const editorRef = shallowRef() // 配置项 const config = { placeholder: '请输入内容...', // 自定义上传图片接口 MENU_CONF: { uploadImage: { server: '/your-server-url', // 后端接收地址 fieldName: 'file', maxFileSize: 2 * 1024 * 1024, async customUpload(file, insertFn) { try { let formData = new FormData(); formData.append('image', file); // 使用axios或其他HTTP客户端发送请求给服务器 const res = await axios.post('/api/upload-image', formData); // 成功后调用insertFn插入返回的结果链接 if (res.status === 200 && res.data.url) { insertFn(res.data.url, '', ''); } } catch(error){ console.error('upload error:', error.message); } } } } } return { editorRef, config } } } ``` 这段代码展示了如何利用 Axios 库向指定 URL 发送文件数据,并将成功响应中的图像路径传递回编辑器以显示已上传的内容[^4]。 #### 处理编辑器生命周期事件 确保当组件卸载时正确销毁编辑器实例,防止内存泄漏等问题发生。 ```javascript onBeforeUnmount(() => { const editor = editorRef.value; if(editor == null ) return ; editor.destroy(); }) ``` 以上就是关于如何在 WangEditor 编辑器中集成自定义图片上传功能的方法介绍。需要注意的是,在实际开发环境中应当根据具体需求调整 API 请求的方式及参数设定等内容。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值