Expo File System无法读取本地图片转Base64问题求助
解决Expo中本地Assets图片转Base64的问题
问题根源
你之前的错误是因为项目根目录assets下的文件属于打包绑定资源(bundled assets),并非存放在FileSystem.documentDirectory目录下。FileSystem无法直接读取asset:///协议路径的文件,必须先通过expo-asset模块将资源加载到本地可访问的路径。
解决方案
使用expo-asset模块加载资源,获取其本地URI后再转Base64,步骤如下:
1. 确保依赖(Expo项目默认已包含,若缺失则安装)
npx expo install expo-asset
2. 修改转换代码
替换原有的转换逻辑,先加载资源再读取:
import { useEffect } from 'react'; import { FileSystem } from 'expo-file-system'; import { Asset } from 'expo-asset'; useEffect(() => { const convertImageToBase64 = async () => { try { // 加载assets目录下的图片资源 const imageAsset = Asset.fromModule(require('../assets/images/super.jpg')); await imageAsset.downloadAsync(); // 从加载后的本地URI读取并转Base64 const base64 = await FileSystem.readAsStringAsync(imageAsset.localUri, { encoding: 'base64', }); console.log('Base64结果:', base64); } catch (error) { console.error('转换失败:', error); } }; convertImageToBase64(); }, []);
关键说明
Asset.fromModule(require('图片路径')):通过require引用资源,让Expo打包时自动识别并包含该资源downloadAsync():将绑定的资源下载到本地可访问路径,生成localUri- 此时
localUri是FileSystem可读取的合法路径,直接用它读取即可转换为Base64
补充说明
- 不要用
asset:///路径直接传给FileSystem,该协议仅用于Expo内部资源引用,无法被FileSystem直接读取 - 若资源未被正确打包,检查
app.json中是否配置了assets字段(Expo默认会自动识别项目根目录的assets文件夹):{ "expo": { "assets": ["./assets/images/"] } }
内容的提问来源于stack exchange,提问作者bob
相关产品推荐
相关产品推荐

