由于项目的上的需要,需要在portal 页面上上传多个文件,而前面的实现都只是上传一个文件,使用的是spring提供的 MultipartFile类。项目中使用的是spring2.5, 在http://static.springsource.org/spring/docs/1.2.x/reference/mvc.html上面也没找到上传多个文件的实现例子。
下面先介绍下上传单个文件的实现:
在项目中定义的bean为:
<bean id="portletMultipartResolver"
class="org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
使用的controller extends SimpleFormController 具体的控制器配置为:
<beanid="sendMailController"class="com.ge.oilandgas.smartportal.quote.controller.SendMailController">
<propertyname="mailSender"ref="mailSender"/>
<property name="commandClass" value="com.ge.oilandgas.smartportal.quote.contextbean.AttachmentFileUploadBen"/>
<propertyname="utility"ref="utility"/>
</bean>
在代码中的实现为
publicvoid onSubmitAction( ActionRequest request,
ActionResponse response,
Object command,
BindException errors) throws Exception {
// cast the bean
AttachmentFileUploadBean bean = (AttachmentFileUploadBean) command;
// get the attached file
MultipartFile attachedfile = bean.getAttachmentFile(); //这样就能得到上传的文件的信息了
}
多个文件上传的实现方法:
上网查找了不少资料,最终找到了一篇外国的文章:
http://dhruba.name/2008/12/27/implementing-single-and-multiple-file-multipart-uploads-using-spring-25/ 里面讲的很清楚。但是我这里没有使用上面那篇文章的方法,不过方式差不多。
1:首先让contrller extends AbstractController
2:在其处理action请求的方法中 添加一个获取多文件的方法:
protectedvoid handleActionRequestInternal(ActionRequest request,
ActionResponse response) throws Exception {
public Map<String,MultipartFile> getAttachmentsMap(ActionRequest request ) throws Exception {
Map<String,MultipartFile> MailAttachFilesMap = new HashMap<String,MultipartFile>();
if (request instanceof MultipartActionRequest) {
logger.debug("==================MulitiPart Request====================");
MultipartActionRequest multipartRequest = (MultipartActionRequest) request;
Map files = multipartRequest.getFileMap();
String fileName = "";
String key = "";
MultipartFile attachedFile = null;
if (files!=null && files.isEmpty() != true && files.size()>0 ) {
for (Iterator fileMapIter = files.keySet().iterator(); fileMapIter.hasNext();)
{
key = (String) fileMapIter.next();
attachedFile = (MultipartFile)(multipartRequest.getFileMap().get(key));
fileName = attachedFile.getOriginalFilename();
MailAttachFilesMap.put(fileName, attachedFile);
System.out.println("===========key======="+key+" ==================== "+fileName);
}
}
}
return MailAttachFilesMap;
}
}
主要是将 request转换为:MultipartActionRequest 。