图片转为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

### 配置TinyMCE富文本编辑器以避免上传图片时自动转为Base64格式 为了防止 TinyMCE 富文本编辑器在处理图片上传时将其换为 Base64 编码,可以通过调整插件设置来实现这一目标。具体来说,可以禁用 `automatic_uploads` 和自定义 `images_upload_handler` 函数[^1]。 以下是详细的配置方法: #### 1. 禁用 Automatic Uploads 通过将 `automatic_uploads` 设置为 `false`,可以阻止 TinyMCE 自动上传图片并将其换为 Base64 格式[^2]。 ```javascript tinymce.init({ selector: '#editor', automatic_uploads: false, // 关闭自动上传功能 }); ``` #### 2. 使用 Custom Image Handler 通过指定 `images_upload_handler` 属性来自定义图片上传逻辑,从而完全控制图片的存储方式和路径[^3]。 ```javascript tinymce.init({ selector: '#editor', images_upload_handler: function (blobInfo, success, failure) { const xhr = new XMLHttpRequest(); const formData = new FormData(); xhr.open('POST', '/your-server-side-endpoint'); // 替换为目标服务器地址 xhr.onload = () => { if (xhr.status < 200 || xhr.status >= 300) { failure('HTTP Error: ' + xhr.status); return; } try { const json = JSON.parse(xhr.responseText); if (!json || typeof json.location !== 'string') { failure('Invalid response from server'); return; } success(json.location); // 返回图片 URL 地址 } catch (e) { failure('JSON Parsing Error: ' + e.message); } }; formData.append('file', blobInfo.blob(), blobInfo.filename()); xhr.send(formData); }, }); ``` 在此代码片段中: - `/your-server-side-endpoint` 是用于接收文件上传请求的服务端 API 路径。 - 成功响应应包含一个名为 `location` 的键,其值为已保存图片的访问 URL[^4]。 #### 3. 额外注意事项 如果希望进一步优化用户体验,还可以考虑以下几点: - **File Field Name**: 如果服务端期望特定字段名,则需修改表单数据中的键名称(默认为 `file`)。例如,在上述代码中更改 `formData.append('custom_field_name', ...)` 即可[^5]。 - **跨域支持**: 当前端与后端部署于不同域名下时,请确保 CORS 头部正确配置以便允许跨源资源共享[^6]。 --- ### 示例完整初始化代码 下面是一个完整的 TinyMCE 初始化示例,展示了如何综合应用以上建议: ```javascript tinymce.init({ selector: '#editor', plugins: ['image code'], toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | image code', automatic_uploads: false, images_upload_handler: function (blobInfo, success, failure) { const xhr = new XMLHttpRequest(); const formData = new FormData(); xhr.open('POST', '/upload-image-api'); xhr.onload = () => { if (xhr.status < 200 || xhr.status >= 300) { failure('HTTP Error: ' + xhr.status); return; } const jsonResponse = JSON.parse(xhr.responseText); if (typeof jsonResponse.url === 'string') { success(jsonResponse.url); } else { failure('Unexpected Server Response.'); } }; formData.append('file', blobInfo.blob(), blobInfo.filename()); xhr.send(formData); } }); ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值