需求:我们在使用uniapp的editor组件时,主要是为了保持输入内容的格式。里面的文字可以有颜色、粗体、排列样式,可以插入图片。就像下面这样。

 一、如何处理图片,好让它在 rich-text组件中显示 ?

逻辑:我们处理图片的时机应该是在最后提交的状态

1. 获取你编辑器输入的内容

//editorCtx是富文本编辑器的实例
editorCtx.getContents({
	success: function(res){
		console.log(res);
    }
})    

下面就是打印的结果,html就是我需要提交到数据库的内容,目前img标签的src里面的值是本地的临时路径,需要将其更换为网络路径

{
    "errMsg": "getContents:ok",
    "text": "做测试,插入图片\n\n",
    "html": "<p>做测试,插入图片</p><p><img src=\"file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_temp/compressed/1689576031612_IMG_20230625_194227_1689420631723.jpg\" data-local=\"file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_temp/compressed/1689576031612_IMG_20230625_194227_1689420631723.jpg\" width=\"100%\" height=\"100%\"></p>",
    "delta": {
        "ops": [
            {
                "insert": "做测试,插入图片\n"
            },
            {
                "attributes": {
                    "data-local": "file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_temp/compressed/1689576031612_IMG_20230625_194227_1689420631723.jpg",
                    "height": "100%",
                    "width": "100%"
                },
                "insert": {
                    "image": "file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_temp/compressed/1689576031612_IMG_20230625_194227_1689420631723.jpg"
                }
            },
            {
                "insert": "\n"
            }
        ]
    }
}

2. 在html的字符串中得到图片的临时路径

//strHtml就是获得的html全部标签
let cc = strHtml.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
    console.log("图片临时路径",capture);
    console.log("每一个img标签",match);
});


3. 将图片上传到OSS或服务器,获取公开访问图片路径               

内容略过

4. 将返回来的 “图片公开访问路径” 替换到html字符串中

注意:img标签不设置宽度和高度,这样在App时就无法正常显示出来

let imgPublic = ["网络路径1","网络路径2","网络路径3"]
let imgIndex = 0; //imgIndex是个下表索引 
let newStr= strHtml.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi,(match, capture)={
	let tempImg = match.replace(/<img(.*?)>/g,`<img src="${imgPublic[imgIndex]}">`);
	imgIndex++;
	return tempImg; //可以将修改的内容返回去
});
console.log("已经替换好网络路径的新字符串",newStr);

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐