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())