图片转为base64存在富文本中

const getBase64 = (e: ChangeEvent<HTMLInputElement>) => {
    // 选择的文件
    let file = e.target.files?.[0];
    // 判断文件是否读取完毕,读取完毕后执行
    if (window.FileReader && file) {
         let reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = function (e) {
             let base64String = e.target?.result;
             // 此处可对该base64进行获取赋值传入后端
             const node: any = {
                 type: 'image', 
                 src: base64String, 
                 alt: file?.name, 
                 children: [{ text: '' }]
             };
             (editor as IDomEditor).insertNode(node);
            }
        }
    }
}

return <>
    <button 
        onClick={e => {
            document.getElementById('input')?.click();
            e.preventDefault();
        }}
    >
        {trigger}
    </button>
    <Input type='file' id='input' onChange={(e) => { getBase64(e) }} />
</>;

       img的src中存放的base64,要交base64存到服务器,服务器返回一个地址替换src的base64,代码如下:

 onFinish={async (value) => {
     let html = value.text;
     const regex = /<img.*?src="(.*?)".*?>/g;
     const images = (html as string).match(regex);
     if (images != null) {
         for (let index = 0; index < images.length; index++) {
               const elem = images[index];
               const div = document.createElement("div");
               div.innerHTML = elem;
               const image = div.children[0];
               if (image === undefined) {
                   throw new Error('无效的文件');
               }
               const filename = image.getAttribute('alt');
               const imageContent = image.getAttribute('src');
               if (filename != undefined && imageContent != undefined) {
                   const res = await 上传到服务器的接口(imageContent, 参数2);
                        if (res.success) {
                             html = html.replace(imageContent, res.data.url);
                        }
               }
         }
         value.text = html;
     }
     return true;
}}              

insertNode用法见以下链接:编辑器 API | wangEditor开源 Web 富文本编辑器,开箱即用,配置简单icon-default.png?t=N7T8https://www.wangeditor.com/v5/API.html#undo

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值