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

IT技术 javascript html image reactjs
2021-05-10 11:10:41

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

谢谢你的答案

1个回答

来自谷歌的文档

  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>
        )
    }
}

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