目的
- 解决富文本编辑器中复制粘贴的图片 base64 字符串过长导致无法存储到数据库的问题
思路
- 通过正则 获取html字符串中里面的所有图片 base64 数组 然后每个图片base64 转成file
- 使用上传文件的函数 上传到服务器上.
- 将上传后获取到的图片访问url 替换成 数据里面的 img 的 src.
代码
export function uploadFile(params) {
let url = `/upload`;
const formData = new FormData();
for (let item in params) {
formData.append(item, params[item]);
}
return fetch(url, {
method: 'POST',
headers: {
Accept: '*/*',
},
body: formData,
})
.then((res) => {
return res.json();
})
.then((responseData) => {
if(responseData && typeof responseData === 'object' && responseData.url){
return responseData;
}
if (responseData && responseData.data) {
return responseData.data;
} else {
throw new Error('文件上传失败');
}
})
.catch(() => {
throw new Error('上传文件失败');
});
}
export default function base64ImgToUrl(htmlContent = ''){
return new Promise((resolve, reject) => {
let splitContent = getImages(htmlContent);
let res = [];
for(let item of splitContent){
if(item && item.includes(';base64,')){
const file = {
base64: item,
};
file.file = base64toFile(item, new Date().getTime());
res.push(file);
}
}
async function DoTaskByForOf() {
for (let item of res) {
const fileResponse = await uploadFile({file:item.file});
if(fileResponse && fileResponse.url){
item.url = fileResponse.url;
}
}
return res;
}
DoTaskByForOf().then((r) => {
resolve(r);
});
})
}
export function getImages(html) {
const regExp = /<img[^>]+src=['"]([^'"]+)['"]+/g;
const result = [];
let temp;
while ((temp = regExp.exec(html)) != null) {
result.push(temp[1]);
}
return result;
}
export function base64toFile(dataUrl = '', filename = 'file') {
let arr = dataUrl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let suffix = mime.split('/')[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime,
});
}