Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
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:

"405 Method not allowed"

Screenshot: enter image description here

Does somebody know how to fix this?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!