Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - ReactJS - display image with ReadableStream as source

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

like image 483
Spook Avatar asked Sep 01 '17 14:09

Spook


People also ask

How do I display image from URL in react?

To display an image from a URL, use the img tag and set its src prop to the complete URL of the image. Optionally set the alt prop to a short description of the image. Copied!

How do I get data from a readable stream?

To retrieve data from a JavaScript ReadableStream object, we need to call a conversion method to convert the ReadableStream to the actual data we can use. to make a GET request to https://httpbin.org/ip with fetch . fetch returns a promise that resolves to a ReadableStream object which we assigned to response .


1 Answers

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

like image 197
ted Avatar answered Oct 01 '22 01:10

ted