使用React Native App从服务器获取图像

时间:2020-03-29 22:39:57

标签: react-native

我正在构建一个带有Springboot Rest API后端和React-Native前端的移动应用程序。 我可以将图片从react-native API上传到Springboot API,并将其作为byte []存储在我的postgres数据库中。 我可以通过Postman测试的简单“获取请求”来检索这张图片。 但是我无法获取该图像并将其显示在我的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);
  }
};

我如何使用此响应将其作为Image balise中的源传递?

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

  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>
  );

1 个答案:

答案 0 :(得分:0)

事实上,我找到了解决方法:

      <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"
  };
};