无法在反应中显示base64图像?

时间:2020-11-05 10:56:33

标签: html reactjs

我从服务器接收数据。我使用在线工具对控制台日志结果进行了编码,这是正确的。

axios.get(`https://localhost:44348/api/user/GetFirstImage`)
      .then(res => {
        const img = res.data;
        this.setState({base64File: "data:image/png;base64," + img});
        console.log(this.state.base64File);
      })

然后我尝试在渲染返回中显示它(我发现了这两种解决方案,但它们都不起作用,我得到了默认的无图像占位符):

<img src={{uri: `data:image/gif;base64,${this.state.base64File}`}} />
<img data-ng-src="data:image/png;base64,{{this.state.base64FileOnlyData}}"/>

我真的没有更多的想法了,谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

在这里,您将data: URL方案前缀,内容类型及其在base64中编码的事实附加到base64数据中。

this.setState({base64File: "data:image/png;base64," + img});

(假设https://localhost:44348/api/user/GetFirstImage返回的是base64编码的数据,而不是图像的更典型的二进制数据。如果没有,那么您将遇到其他问题,需要对图像进行编码。)


然后在这里:

<img src={{uri: `data:image/gif;base64,${this.state.base64File}`}} />

您将data: URL方案前缀,内容类型以及它以base64编码的事实附加到URL。

因此,现在您已将序言应用于数据两次,这将破坏数据。

如果图像是GIF或JPEG,您似乎也无法下定决心。您需要设置正确的内容类型!

此外,您尝试将src属性设置为 Object 而不是 String 。它将转换为字符串-"[object Object]"-将以另一种方式破坏它。


这似乎是解决问题的非常复杂的方法。您是否有理由不从https://localhost:44348/api/user/GetFirstImage提供传统图像(而不是base64数据),而只是将src设置为该URL本身:

this.setState({imageUrl: "https://localhost:44348/api/user/GetFirstImage"});
...
<img src={this.state.imageUrl} />