AngularJS环境下PouchDB图片附件存储、读取及显示问题求助
问题根因与解决方案
错误1原因
- 调用
readAsDataURL报错是因为PouchDB携带attachments: true参数返回的附件data字段默认是Uint8Array(浏览器环境)/Buffer(Node环境)类型,既不是Blob对象,也不是base64字符串,不符合FileReader的参数要求。
错误2原因
- 调用
atob报错有两个可能原因:- 存储时错误将
content_type写为image/jpeg;base64,导致PouchDB返回的字符串附带额外编码标识 - 拿到的base64字符串携带了
data:image/jpeg;base64,前缀,不符合atob的输入要求
- 存储时错误将
解决方案
第一步:修正存储格式
存储附件时content_type仅填写标准MIME类型,不要追加;base64标识:
{ "display_image": { "content_type": "image/jpeg", "data": "/9j/4AAQSkZJRgABAQEAeAB4AAD/..." } }
第二步:根据返回数据类型选择对应处理方式
先打印返回的附件数据确认类型:
console.log(typeof image_data, image_data instanceof Uint8Array, image_data)
情况A:返回数据为Uint8Array/Buffer类型(PouchDB默认情况)
不需要额外转base64,直接生成Blob即可:
const imageBlob = new Blob([image_data], { type: 'image/jpeg' }) const reader = new FileReader() reader.readAsDataURL(imageBlob) reader.onloadend = () => { this.display_image = reader.result }
情况B:返回数据为base64字符串类型
优先使用更简单的直接拼接前缀方案,无需转Blob:
// 自动去除可能存在的data URI前缀,再拼接标准前缀 const pureBase64 = image_data.includes(',') ? image_data.split(',')[1] : image_data this.display_image = `data:image/jpeg;base64,${pureBase64}`
如果确实需要转Blob,使用修正后的转换方法:
public convertB64toBlob(source, type): Blob { // 先移除可能存在的data URI前缀 const base64Str = source.includes(',') ? source.split(',')[1] : source const byteCharacters = atob(base64Str) const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers) return new Blob([byteArray], { type }) }
内容的提问来源于stack exchange,提问作者theSiberman
相关产品推荐
相关产品推荐

