You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native中读取本地文件并转Base64后以JSON格式提交?

嘿,我完全懂你现在的处境——第一次做React开发,用Expo的模板搭了音频录制应用,拿到文件URI却转不成Base64发服务器,试过好几个第三方库都不行,还不想eject项目对吧?别担心,咱们用Expo官方自带的工具就能搞定,不用折腾那些麻烦的第三方依赖,下面一步步来:

解决方案:用Expo FileSystem实现音频转Base64并POST

咱们直接用Expo官方的expo-file-system模块,它完全适配Expo环境,不需要eject,完美解决你的需求。

步骤1:导入Expo FileSystem模块

首先在你的组件文件顶部导入模块,Expo项目默认已经包含这个依赖,不用额外安装:

import * as FileSystem from 'expo-file-system';

步骤2:读取音频文件并转换为Base64

拿到录制好的音频URI(比如file:///path/to/recording.m4a)后,用readAsStringAsync方法读取文件并转成Base64。这里要说明:带file://前缀的URI完全没问题,FileSystem可以直接识别,不用手动去掉,这可能是你之前用第三方库踩坑的点之一。

const convertAudioToBase64 = async (audioUri) => {
  try {
    const base64String = await FileSystem.readAsStringAsync(audioUri, {
      encoding: FileSystem.EncodingType.Base64,
    });
    return base64String;
  } catch (error) {
    console.error('读取音频文件失败:', error);
    throw error; // 抛出错误让上层逻辑处理
  }
};

步骤3:构造JSON请求并发送POST

拿到Base64字符串后,就可以按照服务器要求构造JSON请求体,用原生fetch发送即可:

const sendAudioToServer = async (audioUri) => {
  try {
    // 先转成Base64
    const base64Audio = await convertAudioToBase64(audioUri);
    
    // 构造JSON请求体,字段名根据你的服务器API调整
    const requestBody = JSON.stringify({
      audio_data: base64Audio,
      filename: 'recording.m4a', // 可选,方便服务器识别文件类型
      // 其他需要的字段,比如用户ID、录音时长等
    });

    const response = await fetch('https://your-server-endpoint.com/upload', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json', // 明确告诉服务器是JSON格式
        // 如果服务器需要认证,这里添加Authorization头,比如 Bearer {token}
      },
      body: requestBody,
    });

    if (!response.ok) {
      throw new Error(`请求失败,状态码: ${response.status}`);
    }

    const result = await response.json();
    console.log('音频上传成功:', result);
    return result;
  } catch (error) {
    console.error('上传失败:', error);
  }
};

关键注意事项

  • 权限问题:如果你是用expo-av录制的音频,录制时已经获取了麦克风权限,而读取你自己录制的本地文件,Expo会自动处理权限,不需要额外申请。
  • 避免第三方库的坑:之前你试的Fetch Blob、React Native FS这类库,很多需要eject或者对Expo环境兼容性不好,用官方的FileSystem是最稳妥的选择。
  • 测试建议:你可以在录制完成拿到URI后,直接调用sendAudioToServer(yourAudioUri),比如在录制结束的回调里:
    // 假设这是你的录制完成回调
    const handleRecordingFinished = (recordedUri) => {
      sendAudioToServer(recordedUri);
    };
    

内容的提问来源于stack exchange,提问作者Jeremy E

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:43:56