如何在React应用中查看Oracle数据库存储的BLOB图片?
问题解决方案
核心问题
你直接使用了包含Buffer元数据的USER_IMAGE对象创建Blob,而非提取其中实际的二进制数据数组data,导致生成的Blob不是有效的图片文件。
修正步骤
1. 正确提取二进制数据创建Blob
修改useEffect中创建Blob的代码,改用USER_IMAGE.data作为Blob的数据源:
useEffect(() => { if (userProfile?.data) { const fetchedUser = userProfile?.data; setUser({ userId: fetchedUser.USER_ID, userImage: fetchedUser.USER_IMAGE, }); // 提取Buffer的data数组创建Blob const file = new Blob([fetchedUser?.USER_IMAGE.data], { type: "image/jpeg", }); const fileUrl = URL.createObjectURL(file); setProfileImage(fileUrl); // 组件卸载时清理对象URL,避免内存泄漏 return () => { URL.revokeObjectURL(fileUrl); }; } }, [editUserId, userProfile]);
2. 匹配图片实际格式
确保type参数和Oracle中存储的图片格式一致,如果是PNG就改成"image/png",其他格式对应调整。
3. 确认渲染逻辑正确性
当前img标签直接使用profileImage作为src是正确的,无需再调用URL.createObjectURL(注释的代码保持现状即可)。
额外注意事项
- 每次
useEffect重新执行时会生成新的对象URL,必须在清理函数中回收旧URL,防止内存泄漏。 - 若
userProfile.data或USER_IMAGE可能为空,建议增加空值判断,避免运行时报错。
内容的提问来源于stack exchange,提问作者Gado
相关产品推荐
相关产品推荐

