16

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

1
  • you can convert png image to base64 and you can use it in img element and display. Commented Sep 1, 2017 at 14:18

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.