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

React Native使用RNFS将图片转为Base64并保存失败求助

React Native 图片转Base64并保存(基于RNFS)

问题分析

你的代码存在几个核心问题导致转换失败:

  • 在launchCamera回调外部调用RNFS.readFile,会在用户取消选择/拍照出错时访问不存在的response.assets[0].uri,引发空指针错误
  • 未正确处理不同平台的uri格式(Android可能返回content://开头的路径,RNFS需要适配)
  • then回调中打印的是Promise对象data,而非实际的Base64结果
  • 未利用async函数特性,回调嵌套导致逻辑混乱

修正后的实现代码

import RNFS from 'react-native-fs';
import { launchCamera } from 'react-native-image-picker';
import { Platform } from 'react-native';

const openCamera = async () => {
  const options = {
    storageOptions: {
      skipBackup: true,
      path: 'images',
      mediaType: 'photo'
    },
  };

  // 把回调式API转为Promise,适配async/await
  const response = await new Promise((resolve, reject) => {
    launchCamera(options, (res) => {
      if (res.didCancel) {
        console.log('用户取消拍照');
        reject(res);
      } else if (res.error) {
        console.log('拍照出错:', res.error);
        reject(res);
      } else if (res.customButton) {
        console.log('用户点击自定义按钮:', res.customButton);
        reject(res);
      } else {
        resolve(res);
      }
    });
  });

  try {
    const targetUri = response.assets[0].uri;
    let filePath = targetUri;

    // 处理Android的content://格式路径
    if (Platform.OS === 'android' && filePath.startsWith('content://')) {
      // 部分RNFS版本支持直接读取content uri,若不支持可转为真实路径
      const statResult = await RNFS.stat(filePath);
      filePath = statResult.path;
    }

    // 读取图片并转为Base64
    const base64Data = await RNFS.readFile(filePath, 'base64');
    console.log('转换完成的Base64:', base64Data);

    // 保存Base64到本地文件(示例保存到Documents目录)
    const saveFilePath = `${RNFS.DocumentDirectoryPath}/image_base64.txt`;
    await RNFS.writeFile(saveFilePath, base64Data, 'base64');
    console.log('Base64已保存至:', saveFilePath);
  } catch (err) {
    console.error('转换/保存失败:', err);
  }
};

关键注意事项

  • 权限配置:
    • Android:在AndroidManifest.xml中添加READ_MEDIA_IMAGES(Android 13+)或READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE(低版本)权限
    • iOS:在Info.plist中添加NSCameraUsageDescription和NSPhotoLibraryUsageDescription权限描述
  • 路径兼容性:iOS返回的file://路径RNFS可直接读取,Android的content://路径需通过RNFS.stat转换为真实文件路径
  • 版本兼容:确保react-native-fs和react-native-image-picker的版本与你的React Native版本匹配

内容的提问来源于stack exchange,提问作者Junaid Anwar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:05:20