首页 > 解决方案 > 使用 React Native 应用程序从服务器获取图像

问题描述

我正在构建一个带有 Springboot Rest API 后端和 React-Native 前端的移动应用程序。我可以将 react-native API 中的图片上传到 Springboot API,并将其作为 byte[] 存储在我的 postgres 数据库中。我可以通过 Postman 测试的简单 Get Request 检索这张图片。但我无法获取此图像并将其显示在我的 React Native 应用程序中。

我知道立即使用带有 react native 的 blob 文件存在问题,但我没有看到如何处理它。

这是我的获取功能:

export const getAquariumPicture = async (
  aquariumId: string
): Promise<ImageSourcePropType | any> => {
  const suffixUrl = "api/downloadAquariumPicture/";
  const urlService = urlServer + suffixUrl + aquariumId;
  try {
    const token = await getData("token");
    const response = await fetch(urlService, {
      method: "GET",
      headers: {
        Authorization: token
      }
    });
    return response;
  } catch (error) {
    console.error(error);
  }
};

如何使用此响应将其作为图像应答器中的源传递?

这是我尝试使用照片的方式:

  if (rootStore.tankStore.tankImageState === "pending") {
    rootStore.tankStore.storeGetImageTank();
  }
  const photo = rootStore.tankStore.tankPicture;
  console.log("photo = " + photo);

  return (
    <TouchableOpacity onPress={() => choosePicture()}>
      <Image source={cameraIcon} style={styles.icon} />

      {photo != null ? (
        <Image source={photo} style={styles.photo} />
      ) : (
        <ActivityIndicator />
      )}
    </TouchableOpacity>
  );

标签: react-native

解决方案


事实上我找到了一个解决方案:

      <Image
        source={getAquariumImageSource(RootStore.tankStore.tankList[0].id)}
        style={styles.photo}
      />
      
      
      
      export const getAquariumImageSource = (id: string): ImageSourcePropType => {
  return {
    uri: `${urlServer}api/downloadAquariumPicture/${id}`,
    method: "GET",
    headers: {
      Pragma: "no-cache",
      Authorization: RootStore.memberStore.token
    },
    cache: "reload"
  };
};


推荐阅读