Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java can't upload file with @Pathvariable optional

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"405 Method not allowed"

Screenshot:
enter image description here

Does somebody know how to fix this?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading