Reputation: 111
I am getting an image from backend and trying to display it on the front end using react. I guess that I am not setting properly image into the file when I fetch it. Because, I have the response from the service:
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAg ...
And this is my code:
constructor(props) {
super(props);
this.state = {
file: []
}
}
fetchPicture(){
const {match} = this.props
const id = match.params.id
const { file } = this.state;
fetch("/hunter/picture?page=" + id)
.then(res => res.json())
.then(file => this.setState({ file }));
}
render() {
return(
<Form>
<img alt="" src={`data:image/jpg;base64,${this.state.file}`}/>
</Form>
)
}
}
The most important, I have this on my console:
Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
When I send it from backend, I am setting content type of jpg.
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpg");
Could be also the reason for not displaying because react expects json format? Thank you in advance!
Upvotes: 2
Views: 8144
Reputation: 1339
No need to use fetch and to parse it as json or base64 when you can just set it as src:
<img alt="" src={"/hunter/picture?page=" + this.props.match.params.id} />
Upvotes: 2