I load file in React
<input type='file' id='upload-button' accept='image/*'
onBlur={() => image.onBlur()}
onChange={e => onChangeHandler(e)}/>
Then i do next thing:
const onChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
image.onChangeImage(e)
setFile(e.target.files && e.target.files[0])
}
Then this file i send to the method
DishesService.addDish(dish, file)
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
},
headers: {
"Content-Type": "multipart/form-data",
}
})
} catch (e) {
console.log('Произошла ошибка при добавлении картинки к блюду')
}
}
}
And my Spring Boot controller:
@PutMapping(path = "{dishId}", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<DishEntity> updateDishImage(@PathVariable Long dishId, @RequestParam("file") MultipartFile file) {
DishEntity updateDish = dishService.updateDishImage(file, dishId);
return ResponseEntity.ok(updateDish);
}
Method addDish() saves the object, but what about image: i get exception:
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
And one more question: how to show this image, what i will get it from axios in React?