Javascript - ReactJS - 以 ReadableStream 作为源显示图像 [英] Javascript - ReactJS - display image with ReadableStream as source
本文介绍了Javascript - ReactJS - 以 ReadableStream 作为源显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 PNG 图像作为 ReadableStream,我需要使用这个 ReadableStream 作为源显示 html 元素 img.我应该把它转换成什么吗?或者我该怎么做?
谢谢您的回答
解决方案
来自 Google 的 文档:
- 获取响应的
blob
- 解决它的
Promise
- 使用
URL.createObjectURL
创建本地源 - 将其添加到您的文档(或更新状态)
这是一个例子
import React, { Component } from 'react'功能验证响应(响应){如果(!响应.确定){抛出错误(response.statusText);}返回响应;}导出默认类 componentName extends Component {状态 = {源代码:空}componentDidMount() {获取(`http://localhost:5000/api/images/home`).then(validateResponse).then(response => response.blob()).then(blob => {this.setState({ src: URL.createObjectURL(blob) })})}使成为() {返回 (<div>{ this.state.src &&<img alt="home" src={ this.state.src }></img>}
)}}
就我而言,数据来自 Flask
Python 后端的 send_file
响应
I have PNG image as ReadableStream and I need to display html element img with this ReadableStream as source. Should I convert it to something? Or how can I do it?
Thank you for answer
解决方案
From Google's docs:
- Get response's
blob
- Resolve its
Promise
- Create a local source with
URL.createObjectURL
- Add it to your document (or update state)
Here's an example
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>
)
}
}
In my case, data comes from a send_file
response from a Flask
Python backend
这篇关于Javascript - ReactJS - 以 ReadableStream 作为源显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文