问题
I have configured the access decision manager to check a request before being processed by the servlet the key line is:-
HttpServletRequest request = (HttpServletRequest) RequestContextHolder.currentRequestAttributes().getRequest();
All good. However when the request is enctype="multipart/form-data" how do I get hold of the MultipartHttpServletRequest when RequestContextHolder.currentRequestAttributes().getRequest() only returns HttpServletRequest?
I am using spring 2.5.
回答1:
MultipartHttpServletRequest is n Spring-specific interface for handling multipart form submissions. The default implementation is DefaultMultipartHttpServletRequest, which has a constructor that takes a HttpServletRequest.
So:
HttpServletRequest originalRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
MultipartHttpServletRequest multiPartRequest = new DefaultMultipartHttpServletRequest(originalRequest);
回答2:
Apart from having
<form method=<method> action=<url> enctype="multipart/form-data"></form>
you have to have
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
in your spring configuration file.
Here is nice tutorial on the same
http://techdive.in/spring/spring-file-upload
回答3:
Have you tried casting to MultipartHttpServletRequest?
回答4:
If you are using spring-mvc, make sure you put this line
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
in your app-config.xml.
This worked for me.
回答5:
I don't think you can get DefaultMultipartHttpServletRequest from RequestContextHolder. DefaultMultipartHttpServletRequest really implements HttpServletRequest. But there're 2 request instances if you use CommonsMultipartResolver. One is DefaultMultipartHttpServletRequest instance, and another is HttpServletRequest instance. Actually I don't know how to get the first instance from RequestContextHolder. You can get the second instance from it.
来源:https://stackoverflow.com/questions/6628510/how-to-get-a-multiparthttpservletrequest-from-requestcontextholder