React Native中Image Picker库返回base64: undefined问题求助
解决React Native Image Picker返回base64: undefined的问题
别担心,这个问题其实是Image Picker的默认配置细节导致的,很容易修复!
核心原因
React Native Image Picker 默认不会自动返回base64格式的数据,你需要在配置选项里显式开启这个功能。你的当前代码中缺少了includeBase64: true这个关键配置项,所以response.base64才会返回undefined。
修改后的代码
只需要给你的options对象新增includeBase64: true配置即可:
const chooseFile = (type) => { let options = { mediaType: type, maxWidth: 300, maxHeight: 550, quality: 1, includeBase64: true, // 新增这一行,开启base64数据返回 }; launchImageLibrary(options, (response) => { console.log('Response = ', response); if (response.didCancel) { alert('User cancelled to pick the image'); return; } else if (response.errorCode == 'camera_unavailable') { alert('Camera not available on device'); return; } else if (response.errorCode == 'permission') { alert('Permission not satisfied'); return; } else if (response.errorCode == 'others') { alert(response.errorMessage); return; } console.log('base64 => ', response.base64); console.log('uri => ', response.uri); console.log('width => ', response.width); console.log('height => ', response.height); console.log('fileSize => ', response.fileSize); console.log('type => ', response.type); console.log('fileName => ', response.fileName); setFilePath(response); }); };
额外注意事项
- 如果你的
type参数传入的是video(视频类型),即使开启了includeBase64,库也大概率不会返回base64数据——因为视频的base64体积过大,会严重影响应用性能,这种情况建议直接使用response.uri来处理视频文件。 - 虽然你说功能运行正常,但还是可以再确认下平台权限配置是否正确:
- iOS:在
Info.plist中添加NSPhotoLibraryUsageDescription权限描述 - Android:在
AndroidManifest.xml中添加对应存储权限(根据RN版本和库版本可能需要READ_EXTERNAL_STORAGE或READ_MEDIA_IMAGES等)
- iOS:在
修改后重新运行项目,你就能在控制台看到正常的base64数据了!
内容的提问来源于stack exchange,提问作者Mashood Ali
相关产品推荐
相关产品推荐

