如何显示 API 的“内容类型:image/jpg”响应?(反应本机)

Ara*_*dağ 6 javascript react-native axios expo fastapi

我正在发布图像,并从后端获取处理后的图像作为响应。问题出在响应部分。无论我做什么都无法显示图像。

\n

首先,邮递员工作。所以后端很好,我在邮递员中看到图像响应。无论如何,这是 FastAPI 后端的相关部分:

\n
for img in results.imgs:\n        bytes_io = io.BytesIO()\n        img_base64 = Image.fromarray(img)\n        img_base64.save(bytes_io, format="jpeg")\n    return Response(content=bytes_io.getvalue(), media_type="image/jpeg")\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试过 axios 并获取两者。

\n

Axios 的响应看起来像这样,带有标题:(我得到 200)

\n
"data": "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd",\n  "headers": Object {\n    "content-length": "86387",\n    "content-type": "image/jpeg",\n    "date": "Thu, 05 May 2022 17:45:03 GMT",\n    "server": "uvicorn",\n  },\n
Run Code Online (Sandbox Code Playgroud)\n

如您所见,数据看起来很奇怪。

\n

这是代码:

\n
axios.post("http://10.0.0.3:8000/object-to-img", body, {\n          headers: {\n            "Content-Type": "multipart/form-data",\n          },\n        })\n        .then(function (response) {\n          setImage("data:image/jpeg;base64," + response.data);\n        })\n        .catch(function (error) {\n          console.log(error);\n        });\n
Run Code Online (Sandbox Code Playgroud)\n

这就是我尝试将其形象化的方式:

\n
<Image\n        style={{\n          flex: 1,\n          width: 500,\n          height: 500,\n          resizeMode: "contain",\n        }}\n        source={{ uri: image }}\n      />\n
Run Code Online (Sandbox Code Playgroud)\n

React Native 的 .fetch() 方法根本无法解析该内容。JSON Parse error: Unrecognized token '\xef\xbf\xbd'

\n

无论我做什么,我都无法显示图像。

\n

小智 0

您可以使用 fetchBlob 而不是 axios 从 API 中获取图像,该 API 仅返回编码的 IMAGE

    RNFetchBlob.fetch("GET", obj.url, {
    "content-type": "image/jpeg",
    Authorization: `Bearer ${obj.token}`,
  })
    .then((res) => {
     console.log(res);
    })
    .catch((errorMessage, statusCode) => {
      console.log("errorMessageFETCH", errorMessage);
    });
Run Code Online (Sandbox Code Playgroud)