How to get a MultipartHttpServletRequest from RequestContextHolder?

一世执手 提交于 2019-12-07 10:14:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!