微信小程序(二十五)微信小程序富文本编辑器editor上传图片

3,245 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情

一般在做网站开发的时候,最开始使用的一般都是百度的ueditor,但是这个玩意好久不更新了,功能到时够用,就是UI以及其他的一些套件的视觉效果稍差。

现在一般情况下会使用wangeditor,这个就相对现代的多,可以使用npm/yarn管理。对应的插件也还算丰富,基本使用大概是够了,但是相对于ueditor,功能还是能少一些。

关于微信小程序的富文本编辑器,微信官方给出的示例代码中图片上传功能是将图片上传至小程序的缓存中,代码如下所示:

  insertImage(e) {
    console.log(e);
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        console.log(res);
        that.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          data: {
            id: 'abcd',
            role: 'god'
          },
          width: '80%',
          success: function () {
            console.log('insert image success')
          }
        })
      }
    })
  }

官方给出得到这个也没有问题,实现了前端的图片插入。

我这里封装的editor自定义组件图片上传也是同官方给出的示例一致,也是使用的小程序缓存。

但是在实际开发中,图片我们还是需要上传至服务器中的。

小程序上传文件需要使用到 wx.uploadFile 这个API,官方文档《wx.uploadFile》,这里我不做赘述,直接上代码:

/**
     * @name: 富文本编辑器选择图片
     * @author: camellia
     * @date: 20211223
     */
    insertImage() {
      let self = this;
      wx.chooseImage({
        count: 1,
        success: (res) => {
          // 图片临时存放路径(数据流)
          let filePath = res.tempFilePaths[0];
          // 加密参数
          let str = utils.encryptCode({
            xxxxx: wx.getStorageSync("xxxx"),
            xxxx: self.data.xxxxxx,
          });
          // 发起上传图片请求
          // filePath:选择图片后生成的数据流url
          // constant.request_sign:请求加密字符串
          // str:加密参数
          API.uploadFileOfReport(filePath, constant.request_sign, str).then(
            (res) => {
              // 富文本编辑器插入图片
              self.editorInsertImg(res.data);
            }
          );
        },
      });
    },
    /**
     * @name: 富文本编辑器插入图片
     * @desc: 描述
     * @author: camellia
     * @params :  filePath 图片上传到服务器后后台返回的图片链接地址
     * @date: 20211223
     */
    editorInsertImg(filePath) {
      let self = this;
      // 富文本编辑器插入图片方法
      self.editorCtx.insertImage({
        src: filePath,
        width: "100%",
        data: {
          id: "imgage",
          role: "god",
        },
        // height: '50px',
        // extClass: className
      });
    },
 

以上的代码便是我在实际开发中使用到的图片上传的代码。直接将这部分代码粘贴到上一篇的自定义富文本组件的js文件中即可使用,当然,需要修改一下上传请求部分的代码。

有好的建议,请在下方输入你的评论。

欢迎访问个人博客:guanchao.site

欢迎访问我的小程序:打开微信->发现->小程序->搜索“时间里的”