安卓调试报错:com.facebook.react.bridge.ReadableNativeMap无法转为String
修复React Native安卓上传FormData时的类型转换错误
我之前也碰到过一模一样的问题!在Android上用FormData上传图片时经常会踩这个com.facebook.react.bridge.ReadableNativeMap cannot be cast to java.lang.String的坑,给你几个亲测有效的修复方案:
1. 修正URI格式(最常见原因)
Android上React Native对FormData里的文件URI格式要求很严格,如果你的imageSource是content://开头的内容URI,直接传给FormData会触发类型转换错误。你可以:
- 如果是用图片选择器(比如
react-native-image-picker),直接配置让它返回file://开头的文件URI; - 手动去掉
file://前缀(Android底层不需要这个前缀):
const fileUri = Platform.OS === 'android' ? this.state.imageSource.replace('file://', '') : this.state.imageSource; const file = { uri: fileUri, name: this.state.imageName || 'uploaded-photo.jpg', type: 'image/jpeg', // 建议用jpeg而非jpg,部分安卓设备对MIME类型更敏感 };
2. 不要手动设置Content-Type头
很多人会犯的错误是手动给请求加Content-Type: multipart/form-data,但FormData会自动生成包含boundary的Content-Type头,手动设置会覆盖这个正确的头,导致服务器无法解析请求,进而引发错误。
正确的做法是完全不设置Content-Type,让fetch自动处理:
fetch(config.server + '/upload', { method: 'POST', body: data, headers: { // 只加你需要的其他头,比如Authorization,不要加Content-Type! // 'Authorization': 'Bearer ' + token, }, })
3. 优化错误捕获的显示方式
你的catch里直接alert(err),在Android上Error对象无法被正确alert显示,转成字符串才能看到真实错误信息,方便调试:
.catch((err) => { alert(JSON.stringify(err)); });
完整修改后的代码示例
import { Platform } from 'react-native'; // ... const fileUri = Platform.OS === 'android' ? this.state.imageSource.replace('file://', '') : this.state.imageSource; const file = { uri: fileUri, name: this.state.imageName || 'uploaded-photo.jpg', type: 'image/jpeg', }; const data = new FormData(); data.append('file', file); fetch(config.server + '/upload', { method: 'POST', body: data, headers: { // 按需添加其他请求头,比如token }, }) .then((res) => res.json()) .then((responseData) => { alert(JSON.stringify(responseData)); }) .catch((err) => { alert(JSON.stringify(err)); });
如果按照上面的步骤还是有问题,建议先打印this.state.imageSource的值,确认URI格式是否正确——如果是content://开头的,你需要先把它转换成真实的文件路径,可以借助react-native-fs这类库来完成转换。
内容的提问来源于stack exchange,提问作者kutirie
相关产品推荐
相关产品推荐

