Image from base64 encodes bad in Spring and not shown React

Viewed 34

So, i have an opportunity in my application to add dish to menu. When a add it, i encode it in base64 and send to my server Spring Boot. It decodes this image and saves in db as blob. When i need to get my dishes, i encode images again and sent to the frontend(React). But i get bad encoding:

This is my encoding in React

data:image/png;base64,iVBORw0K...

I send it to my controller:

 @PostMapping
    public ResponseEntity<Dish> saveDish(@RequestBody Dish dish) {
        Dish response = dishService.save(dish);

        return ResponseEntity.ok(response);
    }

@Override
    public Dish save(Dish dish) {
        log.info("Saving dish: {}", dish);

        DishEntity dishEntity = DishEntity.builder()
                .image(Base64.decodeBase64URLSafe(dish.getImage()))
                .price(dish.getPrice())
                .title(dish.getTitle())
                .description(dish.getDescription())
                .category(dish.getCategory())
                .count(1L)
                .totalPrice(dish.getPrice())
                .build();

        DishEntity savedDish;
        try {
            savedDish = dishRepository.save(dishEntity);
        } catch (Exception ex) {
            throw new OperationFailedException("Save dish method failed");
        }

        return Dish.builder()
                .id(savedDish.getId())
                .image(Base64.encodeBase64String(savedDish.getImage()))
                .price(savedDish.getPrice())
                .title(savedDish.getTitle())
                .description(savedDish.getDescription())
                .category(savedDish.getCategory())
                .count(savedDish.getCount())
                .totalPrice(savedDish.getTotalPrice())
                .build();
    }

When i get dishes, a make reversed things. And this is base64, i get from the server:

dataimagepngbase64iVBOR....

And therefore, images are not rendered

I made a method to check image rendering if i send correct values, wrote method, which adds symbols, and when i change base64 encoding from dataimagepngbase64iVBOR.... to data:image/png;base64,iVBORw0K..., a get error in console:

enter image description here

0 Answers
Related