Home > front end >  Java can't upload file with @Pathvariable optional
Java can't upload file with @Pathvariable optional

Time:01-03

I try to build a todoapp with the function to upload files. Now i want to can upload files on a task or simply upload files without tasks. For that i need the @PathVariable Annotation to be optional.

This is my 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);
}

If i try it to upload with a TaskId it works. But when i try it to upload without a taskId it doesnt work. I got the error:

"405 Method not allowed"

Screenshot: enter image description here

Does somebody know how to fix this?

CodePudding user response:

If you want to use the @PathVariable as an optional be sure to bind both paths: @PostMapping(value = {"/upload/{taskId}", "/upload"}).

If you don't post the taskId spring will look for a controller that handles "/upload" instead of "/upload/{taskId}"

Personally i would use RequestParam instead of PathVariable for optional parameters

  • Related