Struts1.x多文件上传问题
最近有个项目要用Struts1.x来做多文件上传,就是用户可以在前台动态添加任意多个文件,然后上传到服务器上。这里文件个数不定,所有没有定义到ActionForm里。于是这时候想到了Apache的FileUpload组件,但是这个组件需要通过解析HttpServletRequest对象来获取所有上传的文件对象。而通过Struts1.x的所有request都被包装成MultipartRequestWrapper,此时再在Action里再来解析request对象就不能获取到上传的FileItem对象。查看了以下Struts1.x的原码,发现,其实我们可以有一种work around的方法来获取FileItem对象,见如下方法
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)
此方法是通过反射来获取Struts类中一个私有的成员变量来获取上传的文件对象的,当然这只是一个临时的解决办法,并且如果要更换Struts版本,最好还是要去再测试一下,以防止类有变化。
说到这里,其实我们还有一种办法可以参考,就是使用Filter,我们可以添加一个FileUploadFilter来在struts处理之前获取FileItem对象并且用request.setAttribute方法放入request对象中。当然这只是一个想法,没有具体测试过。