【问题标题】:how to show image from bytes?如何从字节显示图像?
【发布时间】:2022-01-13 19:31:37
【问题描述】:

我有一个将图像作为字节数据返回的 API,但我不知道如何在 img 标签的 src 中显示这些字节

这是我在结果中得到的一个示例

这就是我使用 axios 来使用 API 的方式

const getFile = async (nombreArchivo) => { 
const tokenApp = window.localStorage.getItem('token')
const {data: res} = await axios.get(`${url}photo-2.jpg`,
{  headers: { Authorization: `${tokenApp}` },responseType: 'json',});
return res;};

【问题讨论】:

    标签: reactjs api axios response-headers


    【解决方案1】:

    {responseType: 'blob'} 添加到您的 axios 配置中。

    然后使用<img src={URL.createObjectURL(responseData)} />显示它。

    【讨论】:

      【解决方案2】:

      您可以将bytes 数组转换为base64 编码并使用它来渲染图像。

      byte[]base64:

      const base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
      

      转化来源here

      拥有base64 后,您可以在标准img 标签的src 字段中使用它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 2017-01-13
        • 2012-03-25
        • 1970-01-01
        • 2013-05-18
        • 2010-12-18
        • 2012-12-24
        相关资源
        最近更新 更多