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
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!
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 .
From Google's docs:
blob
Promise
URL.createObjectURL
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With