[微信小程序踩坑]微信小程序editor富文本组件渲染字符串时,内部图片超出大小导致无法正常渲染或回显(数据传输长度为 3458 KB,存在有性能问题!)

坑一:回显问题

富文本组件:

html 复制代码
    <editor id="editor" name="{{name}}" style="font-size: 28rpx;color: #C9CDD4" read-only="{{true}}" placeholder="{{placeholder}}"  bind:input="onChange11" ></editor>

回显方法:

TypeScript 复制代码
 _onEditorReady: function (html: any) {
      const that = this as any
      that.createSelectorQuery().select('#editor').context(async function (res: any) {
        that.editorCtx = res.context
        await that.editorCtx.setContents({ //将html回显富文本区域
          html,
          success: function (res: any) {
          },
          fail: function (fail: any) {
          },
          complete: function (bbxx: any) {
          }
        })
      }).exec()
    },

bug复现:

数据:"<p>杰佛的撒娇佛是阿达分阶段实施的佛教的撒<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAFUAVgDASIAAhEBAxEB/8QAHQABAAICAwEBAAAAAAAAAAAAAAcIAQYCBAUDCf/EAFwQAAECBQEDBQYNDwoDCQAAAAABAgMEBQYRBwghMRITFEGxIjJRYXHBFRYYIyQ1cnN0gZGh0RczNDY3QlJTVVaTlLKz8CUmJzhDVGJjg5JFZKRERnWChJWio+H/xAAVAQEBAAAAAAAAAAAAAAAAAAAAAv/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/ALRgAlIAAAAAAAAAAAAAAAAAAAAAbhuMKqmOUBy3DcRpcWtNn0Nysj1BIz0XCtg90pGc1tSSjcpL0OJEXq5UREAsvgbirHqq4v5uM/ToYXari/m4z9OBajcNxV/1VMBf+7kT9YQk6ztabTuNzYTZ3okw7HrcwnJ3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t9VLmJNUZBb3zl6iQtrBP6VpP4LA/aeWns21KZatPbLUuWZCTCIrkTevlUDjpvbTLTtWVpLUROaTqNoODVOeQOIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABTbaziJN6hSEs3vujp+0pchSoGuP9ZWme/U/tAthQ5FlPp0CXhoiNhsRqInkPQCJhEQAAAAAAAAAAAAAAAAAU/2yPttpvwdO1S11A9qJb3CFT9rl3SNQKdA8EBE7S3FMYkORgNRNyNQDsoZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJxKh6v/wBZmS+H0wAC3i8QAAAAAAAAAAAAAAAAABUHaG+73SP9DtLdQPrSAAfQAAAAAAAAAAAAAAAAAAAAB//Z" alt="" width="344" height="340" />发动机撒佛啊但是佛教的撒发的撒娇佛就是发撒娇的佛菩萨</p>"

当字符串中包含base64图片,且base64图片超过1024kb就会被微信机制拦截下来(官方文档有说明)导致整个组件无法正常渲染,包括img标签前的文字

解决方案(三种)

1:和后端协调,将base64转为在线url地址(例如oss地址),完美解决

2:对于性能考虑,如果是双端(pc+移动),建议做文件大小判断,文件过大的话建议提示到pc端查看或操作

再数据初始化的时候,先调用如下方法,获得该字符串的实际大小,然后在按需处理,下面做具体举例

TypeScript 复制代码
 getStringSize(str: string) {
      var myString = str;
      // 使用 TextEncoder 将字符串编码为字节数组
      var textEncoder = new TextEncoder();
      var encodedData = textEncoder.encode(myString);
      // 计算字节数
      var byteSize = encodedData.length;
      // 将字节数转换为 KB
      var kbSize = Math.floor(byteSize / 1024);
      return kbSize
    },
TypeScript 复制代码
const str = '你要渲染的富文本字符串'

const realSize = this.getStringSize(str)

if(realSize >=1024) {
    提示用户,该文本域内存在较大图片,请到pc端查看
} else {
    this._onEditorReady(str)
}

3:将base64转为本地url以此绕过大小拦截并成功渲染

非得渲,那就渲吧,思路就是base64有实际大小会被检测到,处于项目原因又不能使用线上url,那就将base64转本地url再替换渲染字符串中的base64,就可以完美绕开大小检测,下面做具体举例

TypeScript 复制代码
 base64ToUrl(base64Data: string, name: string) {
      // 保存的文件名(考虑一个string内可能有多个img标签,使用随机数确保name唯一)
      const FILE_BASE_NAME = 'temp_base64_image' + name + Math.floor(Math.random() * 90);                     
      // 将 base64 数据写入本地文件
      const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.png`;
      fsm.writeFileSync(filePath, base64Data, 'base64');
      // 获取本地图片 URL
      return filePath;
    },

    // 替换字符串中的<img>标签中的base64为本地URL
    replaceBase64WithLocalUrl(inputString: string, name: string) {
      const regex = /<img\s+src="data:image\/[^;]+;base64,([^"]+)"/g; //获取base64数据区间
      // 将base64区间替换为本地图片url绕过setdata1024kb检测
      const replacedString = inputString.replace(regex, (match, base64Data) => { 
        const localImageUrl = this.base64ToUrl(base64Data, name);
        return `<img src="${localImageUrl}"`;
      });
      return replacedString;
    },
TypeScript 复制代码
const str = '你要渲染的富文本字符串'

str = this.replaceBase64WithLocalUrl(str)

this._onEditorReady(str)

坑二:回显图片样式问题

这下图片能正常回显了,无论图片多大多小,但是偶尔有一些超大图会有宽高比例失调原因,第一种方案是用正则给所有img标签设置style=" width:100%;height:100%;object-fit: cover;" 也好,设置**style=" width:100%;height:auto;"**也罢,总之就是不行,于是翻查文档发现

img中如果存在行内style(自带、后台配置),那么自己写的style将会被覆盖,所以正确的方法是给所有img标签设置class ,下面做具体示例

TypeScript 复制代码
this._onEditorReady(str.replace(/<img/g, '<img class="rich-img" '))

.rich-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

至此,所有坑填完


生命不息,学习不止,键盘敲烂,月薪过万!加油,代码人!

相关推荐
燕雀安知鸿鹄之志哉.38 分钟前
攻防世界 web ics-06
网络·经验分享·安全·web安全·网络安全
轻口味1 小时前
【每日学点鸿蒙知识】AVCodec、SmartPerf工具、web组件加载、监听键盘的显示隐藏、Asset Store Kit
前端·华为·harmonyos
alikami1 小时前
【若依】用 post 请求传 json 格式的数据下载文件
前端·javascript·json
V+zmm101341 小时前
基于微信小程序的乡村政务服务系统springboot+论文源码调试讲解
java·微信小程序·小程序·毕业设计·ssm
还这么多错误?!1 小时前
uniapp微信小程序,使用fastadmin完成一个一键获取微信手机号的功能
微信小程序·小程序·uni-app
_院长大人_1 小时前
微信小程序用户信息解密 AES/CBC/NoPadding 解密失败问题
微信小程序·小程序
吃杠碰小鸡1 小时前
lodash常用函数
前端·javascript
emoji1111112 小时前
前端对页面数据进行缓存
开发语言·前端·javascript
泰伦闲鱼2 小时前
nestjs:GET REQUEST 缓存问题
服务器·前端·缓存·node.js·nestjs
m0_748250032 小时前
Web 第一次作业 初探html 使用VSCode工具开发
前端·html