如何在 Spring Boot REST 控制器中使用请求和路径参数?

use*_*483 1 rest spring-boot spring-restcontroller

我有以下上传控制器,它有两个不同类型的参数:1 用于保存文件的路径,2 用于文件本身。我正在寻找正确的方法定义,而不是 2 个在 STS 中给出错误的 @Requestparam。

@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:/";
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*ski 7

您需要对路径参数使用@PathVariableString path注解,并添加一个附加参数 ( ) 来存储它:

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