Home > Mobile >  How to share image between Spring-Boot and React
How to share image between Spring-Boot and React

Time:09-12

I am developing full stack internet-market and i need to send image to my Spring Rest Controller and save it to db. How to do that? I tryed something like that:

setFile(e.target.files && e.target.files[0])

This file is file from <input type="file"/>

After that i send this file to my put method

DishesService.addDish(dish, file)
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 Put method:

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

        return ResponseEntity.ok(updateDish);
    }

I get exception:

org.springframework.web.multipart.MultipartException: Current request is not a multipart request

CodePudding user response:

You are missing the headers:

headers: {
  "Content-Type": "multipart/form-data",
}

in your axios call

CodePudding user response:

Try this :

@RequestMapping(path = "{dishId}", method = PUT, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<DishEntity> updateDishImage(@PathVariable Long dishId, @RequestPart("file") MultipartFile file) {
    // your logic
}

You can also encode you images into base64, then send them to the server-side as string.

  • Related