How to get a MultipartHttpServletRequest from Requ

2019-05-07 14:12发布

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.

5条回答
啃猪蹄的小仙女
2楼-- · 2019-05-07 14:37

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);
查看更多
倾城 Initia
3楼-- · 2019-05-07 14:48

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.

查看更多
混吃等死
4楼-- · 2019-05-07 14:52

Have you tried casting to MultipartHttpServletRequest?

查看更多
beautiful°
5楼-- · 2019-05-07 14:54

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

查看更多
趁早两清
6楼-- · 2019-05-07 14:57

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.

查看更多
登录 后发表回答