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 富文本编辑器,开箱即用,配置简单https://www.wangeditor.com/v5/API.html#undo