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

Spo*_*ook 6 html javascript image reactjs

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

谢谢你的答案

ted*_*ted 6

来自谷歌的文档

  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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

就我而言,数据来自Python 后端send_file的响应Flask