项目使用富文本编辑器发送邮件,邮箱无法预览
项目中有一个问题:我们使用的富文本编辑器编辑好内容后,发送给用户的邮箱,其中如果有图片的话,图片内容无法显示,好奇怪呀!
刚开始以为是邮箱配置的问题,所以我从网上搜了一堆如何配置邮箱,结果找到了这个帖子,让我恍然大悟:
看的出网友也是被这个问题给摩擦的人,但是一语中的:现在邮箱基本不支持打开外部未知的链接了,因为我们用的富文本编辑器是Editor二次封装过来的,用的基本都是默认的配置,这个插件默认处理图片的是时候,是将图片处理成一个外部链接,这也就是为什么发到邮箱的图片没法预览了,那么好,我们该如何解决这个问题呢?毫无疑问,图片展示的时候除了用链接展示,还有一种方案:神奇的base64!
原理
由于安全策略,邮箱会过滤掉外部的未知链接,如果我们直接在上传的时候将图片转换成base64不就行了嘛,因为base64实际上就是一串字符串,这样即可以回显图片,也能避免被邮箱的安全策略屏蔽掉。(亲测有效!)
实现
既然知道原理了,那我们直接扒源码改造就行。废话不多说,直接上代码:
首先找到Editor底层代码有个Editor.vue文件,在editorConfig编辑器配置器里面有个MENU_CONF配置,找到['uploadImage']属性加如下代码即可:
['uploadImage']: {server: getUploadUrl(),
// 单个文件的最大体积限制,默认为 2MmaxFileSize: 5 * 1024 * 1024,
// 最多可上传几个文件,默认为 100maxNumberOfFiles: 10,
// 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []allowedFileTypes: ['image/*'],
// 自定义增加 http headerheaders: {Accept: '*',Authorization: 'Bearer ' + getRefreshToken(), // 使用 getRefreshToken() 方法,而不使用 getAccessToken() 方法的原因:Editor 无法方便的刷新访问令牌'tenant-id': getTenantId()},
// 超时时间,默认为 10 秒timeout: 15 * 1000, // 15 秒
// form-data fieldName,后端接口参数名称,默认值wangeditor-uploaded-imagefieldName: 'file',
// 上传之前触发onBeforeUpload(file: File) {return file},
// 上传进度的回调函数onProgress(progress: number) {
// progress 是 0-100 的数字console.log('progress', progress)},onSuccess(file: File, res: any) {console.log('onSuccess', file, res)},onFailed(file: File, res: any) {console.log('onFailed------', file, res)},onError(file: File, err: any, res: any) {if (err.message.includes('exceeds maximum allowed size')) {message.error('公告内容中上传文件不可大于5MB')} else {message.error('上传失败,请检查文件格式或网络')}return},
// 自定义插入图片customInsert: async (res: any, insertFn: InsertFnType) => {console.log('-edit----------', res);console.log('-edit----------', props.imgToBase64);if(!props.imgToBase64){insertFn(res.data, 'image', res.data);} else {try {const response = await fetch(res.data);const blob = await response.blob();const reader = new FileReader();reader.onloadend = () => {const base64Data = reader.result as string;insertFn(base64Data, 'image', base64Data);};reader.readAsDataURL(blob);} catch (error) {console.error('转换为 Base64 时出错:', error);message.error('转换图片为 Base64 格式失败,请检查网络');}}}// customInsert(res: any, insertFn: InsertFnType) {// console.log('-edit----------', res)// insertFn(res.data, 'image', res.data)// }
},