Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling both Multipart and non-multipart HTTP POSTs in Spring MVC

I have a SpringMVC web service for uploading files which looks like this:

@RequestMapping(value="/upload.json", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> upload(MultipartHttpServletRequest request) {
    // upload the file
}

and everything is dandy. But if one of the consumers posts a non-multipart form, then i get this exception

java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]

Which makes sense.. however I dont want my end users to see 500 servlet exceptions. I want a friendly error message.

I just tried this (to be like a catchall for other POSTs):

@RequestMapping(value="/upload.json", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> upload2(){ 
// return friendly msg 
}

but I get this error:

java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path '/upload.json'

Is there any way to safely handle both multipart and non-multipart POST requests? in one method, or 2 different methods i dont care.

like image 473
icchanobot Avatar asked Jun 15 '11 02:06

icchanobot


1 Answers

Check if the request is a multipart yourself:

@RequestMapping(value="/upload.json", method = RequestMethod.POST) 
public @ResponseBody Map<String, Object> upload(HttpServletRequest request) {
    if (request instanceof MultipartHttpServletRequest) {
        // process the uploaded file
    }
    else {
        // other logic
    }
}
like image 57
matt b Avatar answered Nov 02 '22 23:11

matt b