base64转File对象报错InvalidCharacterError(atob解码失败)求助
解决方案
错误原因分析
- 传入
atob的字符串包含非base64内容:base64Match是match方法返回的数组,第一个元素是完整的data:image/xxx;base64,xxxx格式字符串,直接传给dataURItoBlob会导致atob无法解码前缀部分。 - 硬编码图片类型不合理:固定
type: 'image/jpeg'会导致非jpeg类型图片处理异常,且没有从原始dataURI中提取正确类型。 - 未处理base64格式异常:部分base64字符串可能存在空格、换行或长度不符合4的倍数的情况,会触发
atob解码错误。
修复后的代码
async convertFile(data) { const base64Regex = /data:image\/(\w+);base64,([\s\S]+)/; const base64Match = this.Frm.value.content.match(base64Regex); if (base64Match) { // 提取图片类型和纯base64字符串 const imageType = base64Match[1]; const base64String = base64Match[2]; let fileData = this.dataURItoBlob(base64String, imageType); console.log('filedata', fileData.size); } } dataURItoBlob(base64String, imageType) { // 清理base64字符串中的非有效字符,补全padding base64String = base64String.replace(/\s+/g, ''); const padding = base64String.length % 4; if (padding > 0) { base64String += '='.repeat(4 - padding); } try { const byteString = window.atob(base64String); const arrayBuffer = new ArrayBuffer(byteString.length); const int8Array = new Uint8Array(arrayBuffer); for (let i = 0; i < byteString.length; i++) { int8Array[i] = byteString.charCodeAt(i); } // 使用提取到的正确图片类型 const blob = new Blob([int8Array], { type: `image/${imageType}` }); return blob; } catch (error) { console.error('base64解码失败:', error); throw error; } }
关键修复点
- 正确提取纯base64内容和图片类型:从
match结果中取出第二个元素作为纯base64字符串,第一个捕获组获取图片格式(如png、jpeg)。 - 预处理base64字符串:移除所有空白字符,补全base64所需的padding(确保长度是4的倍数),避免
atob解码报错。 - 动态设置Blob类型:根据原始dataURI中的图片类型设置Blob的
type属性,保证文件类型正确。 - 增加错误捕获:在
dataURItoBlob中添加try-catch,便于排查解码失败的具体原因。
如果你的base64Match是包含多个base64数据的数组(比如匹配了多个图片),可以调整正则为全局匹配,再遍历处理:
async convertFile(data) { // 全局匹配所有图片dataURI const base64Regex = /data:image\/(\w+);base64,([\s\S]+?)(?=(data:image|$))/g; let match; const imageList = []; while ((match = base64Regex.exec(this.Frm.value.content)) !== null) { const imageType = match[1]; const base64String = match[2]; const blob = this.dataURItoBlob(base64String, imageType); imageList.push(blob); console.log('filedata', blob.size); } // 后续可以使用imageList中的Blob对象上传 }
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

