admin管理员组

文章数量:1278881

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

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

Share Improve this question asked Sep 1, 2017 at 14:11 SpookSpook 3733 gold badges6 silver badges16 bronze badges 1
  • you can convert png image to base64 and you can use it in img element and display. – Kumar Commented Sep 1, 2017 at 14:18
Add a ment  | 

1 Answer 1

Reset to default 7

From Google's docs:

  1. Get response's blob
  2. Resolve its Promise
  3. Create a local source with URL.createObjectURL
  4. 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 ponentName extends Component {

    state = {
        src: null
    }

    ponentDidMount() {
        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 es from a send_file response from a Flask Python backend

本文标签: htmlJavascriptReactJSdisplay image with ReadableStream as sourceStack Overflow