React-Native使用Axios上传WAV音频至谷歌云服务器遇空文件问题
问题分析与修复方案
你的代码存在几个关键问题,导致服务器无法正确接收文件:
1. FormData 文件添加方式错误
你将base64编码后的字符串直接追加到FormData,但服务器需要的是标准文件对象而非纯字符串。而且你对blobToBase64返回的dataURL(已带data:audio/wav;base64,前缀)再次执行base64编码,属于重复操作,完全没必要。
在React-Native中,直接用本地文件路径构造符合规范的对象即可添加到FormData:
formData.append('file', { uri: result.path, // iOS需带file://前缀,Android不需要,可根据平台判断 name: `recording.${fileType}`, type: `audio/${fileType}` });
2. 手动设置Content-Type导致解析失败
Axios处理FormData时会自动生成包含boundary的multipart/form-data请求头,手动设置'Content-Type': 'multipart/form-data'会丢失关键的boundary参数,服务器无法正确解析FormData内容,直接移除该配置即可。
3. 冗余的Blob转换步骤
用XMLHttpRequest获取本地文件Blob完全多余,React-Native的FormData支持直接使用本地文件路径,省去转Blob和base64的步骤,既简化代码又避免编码错误。
修正后的完整代码
voiceSearchApi 函数
const voiceSearchApi = async (form: any) => { try { const res = await axios.post(apiUrl, form); console.log({ res: res.data }); return res; } catch (err) { console.log(err.response); throw err; } };
stopRecording 函数
import { Platform } from 'react-native'; const stopRecording = async () => { try { const result: { path: string } = await SoundRecorder.stop(); console.log('Stopped recording:', result?.path); setIsRecording(false); setFilePath(result?.path); const uriParts = result?.path.split('.'); const fileType = uriParts[uriParts.length - 1]; console.log({ fileType }); const formData = new FormData(); // 根据平台适配文件URI前缀 const fileUri = Platform.OS === 'ios' ? `file://${result.path}` : result.path; formData.append('file', { uri: fileUri, name: `recording.${fileType}`, type: `audio/${fileType}` }); const res = await voiceSearchApi(formData); } catch (err) { console.error('Failed to stop recording:', err); } };
额外注意事项
- 确保应用已配置正确的文件访问权限(iOS需在Info.plist添加录音权限,Android需在AndroidManifest.xml添加相关权限)
- 确认谷歌云服务器接口接收
multipart/form-data类型请求,且参数名file与FormData中的key一致
内容的提问来源于stack exchange,提问作者Code_war
相关产品推荐
相关产品推荐

