Search code examples
spring-bootrestspring-restcontroller

How to use request and path parameters in a Spring Boot REST controller?


I have the following upload controller which has two params with DIFFERENT type: 1 is for the path the file will be saved to and 2 the file itself. I'm looking for the correct method definition instead of 2 @Requestparam which give error in STS.

@PostMapping("/{path}/")
public String handleFileUpload(@RequestParam("path"), @RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    
    filesStorageService.store(file);
    redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
    
    return "redirect:/";
}

Solution

  • You need to use the @PathVariable annotation for the path parameter and add an additional argument (String path) to store it:

    @PostMapping("/{path}/")
    public String handleFileUpload(
       @PathVariable("path") String path,
       @RequestParam("file") MultipartFile file,
       RedirectAttributes redirectAttributes) {
       [...]