You need to enable JavaScript to run this app. 上传图片前调用压缩函数遇ReadableNativeMap转String错误
优惠活动
大模型
产品
解决方案
定价
更多

上传图片前调用压缩函数遇ReadableNativeMap转String错误

报错根因定位

你遇到的ReadableNativeMap cannot be cast to java.lang.String报错,就是参数传递逻辑的问题,核心来自三处代码书写疏漏,和上层业务逻辑无关:

  • 压缩方法调用时漏写await:压缩函数本身是async异步方法,调用时没有等待异步执行完成,直接把pending状态的Promise对象传给了后续的文件加载逻辑。原生层尝试把传入值当字符串路径解析时,拿到的是结构化的原生Map结构,直接触发类型转换失败。
  • 压缩结果的返回值字段取错:Expo ImageManipulator处理完成后的返回结果,本地图片路径存在uri字段下,原代码写的是返回manipResult.url,就算补上await,取到的也是undefined值,没法正常读取文件。
  • 压缩方法的入参结构不符合API规范:新版Expo ImageManipulator的manipulateAsync方法,第二个参数要求传入操作动作数组,原代码直接把压缩率、格式配置当第二个参数的对象传入,导致原生层解析参数时拿到结构不匹配的对象,进一步放大类型转换报错。
修正后的可运行代码

压缩函数调整

const compressimagestuff = async (uncompressedImageUri) => {
  const manipResult = await ImageManipulator.manipulateAsync(
    uncompressedImageUri,
    // 按API要求用数组包裹操作项,无尺寸调整需求可留空配置
    [{}],
    { 
      compress: 0.3, 
      format: ImageManipulator.SaveFormat.JPEG 
    }
  );
  // 取正确的返回字段
  return manipResult.uri;
};

上传函数调整

const uploadImageAsync = async (uncompressedImage) => {
  // 补上await,拿到压缩后的本地图片uri字符串
  let compressedImageUrl = await compressimagestuff(uncompressedImage);
  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      console.log(e);
      reject(new TypeError('Network request failed'));
    };
    xhr.responseType = 'blob';
    xhr.open('GET', compressedImageUrl, true);
    xhr.send(null);
  });

  const ref = firebase
    .storage()
    .ref('Front/')
    .child(await uuid.v4())
  const snapshot = await ref.put(blob);
  blob.close();
  return await snapshot.ref.getDownloadURL();
};
验证校验点
  • 可以在拿到compressedImageUrl后打印日志,确认输出内容是类似file:///data/xxx.jpg的本地路径字符串,不是Promise对象或原生Map结构,此时就不会再触发类型转换报错。
  • 拍照功能运行正常,是因为拍照环节的参数都是直接传入给原生方法,没有跨异步的Promise传递问题,所有报错都集中在压缩环节的调用和返回值处理上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 01:36:04