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

React Native-Share映射数组到urls遇uriString错误如何解决?

解决react-native-share的urls字段Error: uriString问题

问题原因

你直接将base64字符串数组传给urls字段,但react-native-share的urls要求传入**本地文件URI(file://开头)**或远程HTTP/HTTPS URL,base64字符串无法被识别为合法的URI,因此抛出Error: uriString。

解决方案

需要先将base64字符串转换为本地文件URI,再传入urls字段。可以借助react-native-fs库完成文件写入操作:

1. 依赖安装

npm install react-native-fs --save
# 或使用yarn
yarn add react-native-fs

2. 编写base64转文件URI工具函数

import RNFS from 'react-native-fs';

/**
 * 将base64字符串转换为本地文件URI
 * @param {string} base64String - 带前缀的base64图片字符串
 * @param {string} fileName - 保存的文件名
 * @returns {Promise<string>} 文件URI
 */
const base64ToFileUri = async (base64String, fileName) => {
  // 移除base64前缀(如"data:image/jpeg;base64,")
  const pureBase64 = base64String.replace(/^data:image\/\w+;base64,/, '');
  // 定义文件保存路径
  const filePath = `${RNFS.DocumentDirectoryPath}/${fileName}`;
  // 写入base64数据到文件
  await RNFS.writeFile(filePath, pureBase64, 'base64');
  // 返回file URI
  return `file://${filePath}`;
};

3. 修改分享逻辑

先将所有base64图片转换为文件URI数组,再传入分享配置:

try {
  // 批量转换base64数组为文件URI数组
  const imageUris = await Promise.all(
    imagesBase64.map((base64, index) => 
      base64ToFileUri(base64, `shared_job_image_${index}.jpg`)
    )
  );

  const shareConfig = {
    title: `Shared Job from Group ${groupID}`,
    email: shareEmail,
    message: `Group ID ${groupID} | License Number ${data.LicenseNumber}
Model: ${data.Manufacturer} ${data.Model} ${data.ProductionYear}
Images:`,
    urls: imageUris
  };

  const shareResponse = await Share.open(shareConfig);
  console.log(JSON.stringify(shareResponse));

  // 分享成功后清理临时文件(可选)
  if (shareResponse.action === Share.sharedAction) {
    await Promise.all(
      imageUris.map(uri => RNFS.unlink(uri.replace('file://', '')))
    );
  }
} catch (e) {
  console.log('Error => ', e);
}

额外注意事项

  • Android平台需确保已申请文件读写权限,可在AndroidManifest.xml中添加:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
  • iOS平台无需额外权限,但需确保DocumentDirectoryPath可正常访问
  • 如果你的图片是远程资源,直接传入图片的HTTP URL数组即可,无需转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:12:14