How to display image using React JS Front end? (When Spring boot backend is working)

Viewed 340

This is Spring boot Back end API, it works perfectly well!

@GetMapping("/image/{root}")
    public ResponseEntity<byte[]> getFile(@PathVariable String root) {

        String filename = "";
        cost temp = new cost();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("image/png"));
        List<cost> costs = costRepository.findAll();
        for (cost cost : costs) {
            System.out.println(root);
            if (cost.getRoot().equals(root)) {
                filename = cost.getRoot();
                temp = cost;
                break;
            }
        }
        headers.add("content-disposition", "inline;filename=" + filename);

        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(temp.getImage(), headers, HttpStatus.OK);
        return response;
    }

Frontend Attempt- This is the React JS Frontend

import React, { Component } from 'react';
import CostService from '../services/CostService';

class image extends Component {

    constructor(props) {
        super(props)

        this.state = {
                imageDisplay: ''
        }
    }
    
    componentDidMount(){
        CostService.showImage().then((res) => {
            this.setState({ imageDisplay: res.data});
            console.log(res.data);
        });
}

    render() {
        return (
            <div>
                hi
                <img src={this.state.imageDisplay}></img>
            </div>
        );
    }
}

export default image;

This is the frontend service

showImage() {
        return axios.get(user_base_url + '/image/3');
    }

Output Image:- Output Image

I don't know how to use React JS Frontend to display the image. I am stuck here. Please advise!

0 Answers
Related