A problem requesting base64 encoded file React - Spring Boot

Viewed 23

I have a problem with sharing image between Spring and React. What i do:

I get file from input:

<input type='file' id='upload-button' accept='image/*'
  onBlur={() => image.onBlur()}
  onChange={e => onChangeHandler(e)}/>

Then my handlerMethod with base64Encoder:

    const onChangeImage = async (e: any) => {
        const file = e.target.files[0]
        const base64 = await convertToBase64(file)
        setValue(base64)
    }

export const convertToBase64 = (file: any) => {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        fileReader.onload = () => {
            resolve(fileReader.result)
        }
        fileReader.onerror = (error) => {
            reject(error)
        }
    })
}

And after that i send this file to method:

DishesService.addDish(dish, image.value)

This method:

export default class DishesService {
    static async addDish(dish: IDish, file: any) {
        try {
            await axios.post<IDish>('http://localhost:8080/dishes', dish)
                .then(response => {
                    this.updateDishImage(response.data.id, file)
                })
        } catch (e) {
            console.log('произошла ошибка при добавлении блюда')
        }
    }

    static async updateDishImage(id: number | undefined, image: any) {
        try {
            await axios.put('http://localhost:8080/dishes/' + id, {}, {
                params: {
                    file: image
                }
            })
        } catch (e) {
            console.log('Произошла ошибка при добавлении картинки к блюду')
        }
    }
}

And my Spring Boot controller:

    @PutMapping(path = "{dishId}")
    public ResponseEntity<DishEntity> updateDishImage(@PathVariable Long dishId, @RequestParam("file") String base64File) {
        DishEntity updateDish = dishService.updateDishImage(base64File, dishId);

        return ResponseEntity.ok(updateDish);
    }

Method:

@Override
    public DishEntity updateDishImage(String base64File, Long id) {
        DishEntity dishById = findById(id);

        byte[] byteImage = Base64.decodeBase64(base64File);
        dishById.setImage(byteImage);

        DishEntity updatedDish;
        try {
            updatedDish = dishRepository.save(dishById);
        } catch (Exception ex) {
            throw new OperationFailedException("Update dish image method failed!");
        }

        return updatedDish;
    }

Whan i do my code, I get exception:

Last encoded character (before the paddings if any) is a valid base 64 alphabet but not a possible value. Expected the discarded bits to be zero.

If you faced with this problem, please, help me to fix this error

0 Answers
Related