user2304483
user2304483

Reputation: 1644

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:/";
}

Upvotes: 1

Views: 6960

Answers (1)

Gregor Zurowski
Gregor Zurowski

Reputation: 2346

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) {
   [...]

Upvotes: 7

Related Questions