gpt4 book ai didi

Javascript - ReactJS - 以 ReadableStream 作为源显示图像

转载 作者:行者123 更新时间:2023-11-28 02:37:51 24 4
gpt4 key购买 nike

我有 PNG 图像作为 ReadableStream,我需要以这个 ReadableStream 作为源显示 html 元素 img。我应该把它转换成什么吗?或者我该怎么做?

谢谢你的回答

最佳答案

来自谷歌的docs :

  1. 获取响应的blob
  2. 解决其Promise
  3. 使用 URL.createObjectURL 创建本地源
  4. 将其添加到您的文档(或更新状态)

举个例子

import React, { Component } from 'react'


function validateResponse(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}

export default class componentName extends Component {

state = {
src: null
}

componentDidMount() {
fetch(`http://localhost:5000/api/images/home`)
.then(validateResponse)
.then(response => response.blob())
.then(blob => {
this.setState({ src: URL.createObjectURL(blob) })
})

}


render() {
return (
<div>
{ this.state.src && <img alt="home" src={ this.state.src }></img> }
</div>
)
}
}

在我的例子中,数据来自 Flask Python 后端的 send_file 响应

关于Javascript - ReactJS - 以 ReadableStream 作为源显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46002113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com