服务器在 axios 中发送原始图像,如何将其转换为 base64 或其他方式使用此图像

问题描述

从以下链接中,我得到了一张图片。不幸的是,它在网络的检查元素的预览选项卡中显示了图像。但在 res.data 中,它显示了损坏的文本。我将如何能够在 img 标签中使用此图像,例如 .我还在控制台和预览中分享了它返回给我的内容

export const getProfilePhoto = async (userType) => {
    return await axios.get(`${API_URL}/staff/profile-photo`,{ headers : authHeader(userType) })
    .then((res) => {
        console.log(res.data)
    })
}

这是它在控制台中显示内容

enter image description here

这是它在预览中显示内容

enter image description here

非常期待一些建议和解决方

对于任何错误,我深表歉意。

解决方法

理想情况下,您可以找到一种无需额外标题即可访问此图像的方法,因此您可以直接让浏览器处理它:

<img src="{API_URL}/staff/profile-photo" />

如果您不能这样做,那么您将需要获取一个 blob 并创建一个对象 URL。

fetch(
  `${API_URL}/staff/profile-photo`,{
    headers: authHeader(userType)
  }
).then(res => res.blob()).then((blob) => {
  img.src = URL.createObjectURL(blob);
});