package com.raven.springbootthymeleafrecipeorganizer.controller; // imports are omitted @Controller @RequestMapping("/recipe") public class RecipeController { private final RecipeService recipeService; @Autowired public RecipeController(RecipeService recipeService) { this.recipeService = recipeService; } @GetMapping("/view/{id}") public ModelAndView getRecipe(@PathVariable(name = "id") int id) { Recipe recipe = this.recipeService.findById(id); recipe.setImageName(recipe.getRecipeImage().getOriginalFileName()); recipe.setImageURL(MvcUriComponentsBuilder .fromMethodName(RecipeController.class, "getImage", recipe.getRecipeImage().getOriginalFileName()) .build().toString()); ModelAndView modelAndView = new ModelAndView("recipe/viewrecipe"); modelAndView.addObject("recipe", recipe); return modelAndView; } @GetMapping("/list") public ModelAndView getRecipeList() { List<Recipe> recipes = new ArrayList<>(); List<Recipe> recipeList = this.recipeService.findAll(); recipeList.forEach(t -> { t.setImageName(t.getRecipeImage().getOriginalFileName()); t.setImageURL(MvcUriComponentsBuilder .fromMethodName(RecipeController.class, "getImage", t.getRecipeImage().getOriginalFileName()) .build().toString()); recipes.add(t); }); ModelAndView modelAndView = new ModelAndView("recipe/recipelist"); modelAndView.addObject("recipes", recipes); return modelAndView; } @GetMapping("/new") public ModelAndView newRecipe() { ModelAndView modelAndView = new ModelAndView("recipe/newrecipe"); modelAndView.addObject("recipe", new Recipe()); return modelAndView; } @PostMapping("/save") public String saveRecipe(@ModelAttribute("recipe") Recipe recipe, @RequestParam("inputFile") MultipartFile multipartFile) { Recipe savedRecipe = this.recipeService.saveRecipe(recipe, multipartFile); return "redirect:/recipe/list"; } @GetMapping("/images/{fileName}") public ResponseEntity<Resource> getImage(@PathVariable(name = "fileName") String fileName) { Resource file = this.recipeService.loadImage(fileName); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"") .body(file); } }