我尝试构建一个具有上传文件功能的todoapp。现在我想可以在任务中上传文件,或者只是在没有任务的情况下上传文件。为此,我需要 @PathVariable 注释是可选的。
这是我的 Controller :
@PostMapping("/upload/{taskId}")
private ResponseEntity<String> uploadFile(@CurrentUser UserPrincipal userPrincipal, @RequestParam("file") MultipartFile[] file, @PathVariable(required = false) String taskId) {
fileService.upload(userPrincipal.getUser(), file, taskId);
return new ResponseEntity<>("File uploaded", HttpStatus.OK);
}
如果我尝试使用 TaskId 上传它,它会起作用。但是当我尝试在没有 taskId 的情况下上传时,它不起作用。我得到了错误:
“405方法不允许”
有人知道如何解决这个问题吗?
最佳答案
如果你想使用 @PathVariable
作为可选,请确保绑定(bind)两个路径:@PostMapping(value = {"/upload/{taskId}", "/upload"})
.
如果您不发布 taskId
,spring 将查找处理 "/upload"
而不是 "/upload/{taskId}"的 Controller
我个人会使用 RequestParam
而不是 PathVariable
作为可选参数
关于Java无法上传带有@Pathvariable可选的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70564484/