1

Can anyone guide me how to get the image data from the spring boot backend to a react front end?. Im basically saving the file in the server and by using the path saved in the db ill be retrieving the image.

So far I managed to get the file as an byte array to the front end and it can be checked in the network. I need help displaying it in a <img/> Thank you

lp_nave
  • 244
  • 3
  • 17
  • 1
    Does this answer your question? [How to display an image stored as byte array in HTML/JavaScript?](https://stackoverflow.com/questions/20756042/how-to-display-an-image-stored-as-byte-array-in-html-javascript) – Heretic Monkey Jan 28 '20 at 17:10
  • @HereticMonkey Yes it kinda does.. can i set the value to a state and then use that in the src? then i can avoid all the `document.getElementById` section right? – lp_nave Jan 28 '20 at 17:17
  • @HereticMonkey i tried them both. whats in the link and also what i suggested. It displays the broken image icon – lp_nave Jan 28 '20 at 17:21

1 Answers1

1

Recently worked on this topic. Sharing my experience

React

const [imageData, setImageData] = React.useState({});

  const getImage = (url) => {
    axios.get(url).then((response) => {
      setImageData(response);
    });
  };

  const displayImage = () => {
    return (
      <div className="img">
        <img
          src={`data:image/jpeg;base64,${imageData}`}
          alt=""
        />
      </div>
    );
  };

Controller

@GetMapping("/{id}")
    public ResponseEntity<byte[]> getFile(@PathVariable Long id) {
       FileObject fileObject =  fileRepository.findById(id).get();
       byte[] base64encodedData = Base64.getEncoder().encode(fileObject.getData());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + 
                 fileObject.getName() + "\"")
                .body(base64encodedData);
    }

Note : It is important that the image data is Base64 encoded in the Server

Base64.getEncoder().encode(fileObject.getData())
jfk
  • 4,335
  • 34
  • 27