0

I want to download an image from my REST API with axios and display it in an img tag. Can I do this without locally saving the file?

I had used <img src="localhost/api/imgs/1"/> so far, but I'm securing the endpoint with token management now.

Any ideas how this is normally done?

Rob
  • 14,746
  • 28
  • 47
  • 65
phoebus
  • 1,280
  • 1
  • 16
  • 36

1 Answers1

0

It looks like you are also using React. Are you able to save the image to the state and then pass it along as the source?

import React, { Component } from "react";
import API from 'wherever you are calling axis from';

class YourClass extends Component {
state = {
img = ""
}

getImage = () => {
API.getImage()
.then(res =>
this.setState({ img: res.data })
)
.catch(error => console.log(error)
}

render() {
<div>
<img src={this.state.img}>
</div>
}
}
CB721
  • 256
  • 4
  • 15
  • I did try it like that but unfortunately it doesn't render the image data this way. Do I have to convert the `res.data` first before it can be used as a `src` attribute? – phoebus Sep 07 '19 at 00:10
  • Converting it like [here](https://stackoverflow.com/questions/44611047/get-image-from-server-and-preview-it-on-client) works, maybe update your answer including this. – phoebus Sep 07 '19 at 00:18