开发者

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

开发者 https://www.devze.com 2023-03-13 05:33 出处:网络
I have a SpringMVC web service for uploading files which looks like this: @RequestMapping(value=\"/upload.json\", method = RequestMethod.POST)

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 hand开发者_如何学Pythonler 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.


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
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消