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

React Native中使用Axios从API获取图片无法显示的问题求助

解决React Native中Axios获取二进制图片无法显示的问题

你的问题核心是没把后端返回的arraybuffer转换成React Native <Image>组件能识别的格式。直接用response.request._response的原始字符串无效,必须将二进制数据转成Base64格式的Data URI。

具体修正步骤

  • 调整state初始值:单张图片无需用数组,改为null更合理
  • 将arraybuffer转换为Base64字符串
  • 构建符合标准的Data URI格式(data:image/png;base64,xxxxxx)

修改后的完整代码

import React, { useEffect, useState } from "react";
import { View, Image, ActivityIndicator, StyleSheet, Text } from "react-native";
import axios from "axios";

const BlogEscolar = () => {
  const [imageUri, setImageUri] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchImage = async () => {
      try {
        const response = await axios.get(
          "http://x.x.x.x:5001/api/FTPService/download",
          {
            params: { fileName: "image.png" },
            responseType: "arraybuffer",
          }
        );
        if (response.status === 200) {
          // 把arraybuffer转成Base64字符串
          const base64String = Buffer.from(response.data).toString('base64');
          // 构建Data URI,注意匹配图片MIME类型(这里是png)
          const dataUri = `data:image/png;base64,${base64String}`;
          setImageUri(dataUri);
        }
      } catch (error) {
        console.log("Error fetching image:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchImage();
  }, []);

  if (loading) {
    return <ActivityIndicator size="large" color="#0000ff" />;
  }

  return (
    <View style={styles.container}>
      {imageUri ? (
        <Image
          style={styles.image}
          source={{ uri: imageUri }}
        />
      ) : (
        <Text>图片加载失败</Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    width: 75,
    height: 75,
    borderRadius: 37.5,
  },
});

export default BlogEscolar;

补充说明

  1. 如果后端返回的是JPG等其他格式,要把Data URI里的image/png改成对应MIME类型(比如image/jpeg)
  2. 若React Native环境不支持Buffer,可以用以下方法转换:
function arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

然后替换Buffer.from(response.data).toString('base64')为arrayBufferToBase64(response.data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:52:24