简体   繁体   中英

How to share image between Spring-Boot and React

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

You are missing the headers:

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

in your axios call

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM