Action fileUpload的定义改为如下所示:
< action name ="fileUpload" class ="tutorial.FileUploadAction" >
< interceptor-ref name ="fileUpload" >
< param name ="allowedTypes" >
image/bmp,image/png,image/gif,image/jpeg
</ param >
</ interceptor-ref >
< interceptor-ref name ="defaultStack" />
< result name ="input" > /FileUpload.jsp </ result >
< result name ="success" > /ShowUpload.jsp </ result >
</ action >
清单11 修改后的配置文件
显而易见,起作用就是fileUpload******的allowTypes参数。另外,配置还引入defaultStack它会帮我们添加验证等功能,所以在出错之后会跳转到名称为“input”的结果,也即是FileUpload.jsp。
发布运行应用程序,出错时,页面如下图所示:
清单12 出错提示页面
上面的出错提示是Struts 2默认的,大多数情况下,我们都需要自定义和国际化这些信息。通过在全局的国际资源文件中加入“struts.messages.error.content.type.not.allowed=The file you uploaded is not a image”,可以实现以上提及的需求。对此有疑问的朋友可以参考我之前的文章《在Struts 2.0中国际化(i18n)您的应用程序》。
实现之后的出错页面如下图所示:
清单13 自定义出错提示页面
同样的做法,你可以使用参数“maximumSize”来限制上传文件的大小,它对应的字符资源名为:“struts.messages.error.file.too.large”。
字符资源“struts.messages.error.uploading”用提示一般的上传出错信息。
在Struts 2中实现文件上传(6)
时间:2011-03-23
多文件上传
与单文件上传相似,Struts 2实现多文件上传也很简单。你可以将多个<s:file />绑定Action的数组或列表。如下例所示。
< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >
< s:file label ="File (1)" name ="upload" />
< s:file label ="File (2)" name ="upload" />
< s:file label ="FIle (3)" name ="upload" />
< s:submit />
</ s:form >
清单14 多文件上传JSP代码片段
如果你希望绑定到数组,Action的代码应类似:
private File[] uploads;
private String[] uploadFileNames;
private String[] uploadContentTypes;
public File[] getUpload() { return this .uploads; }
public void setUpload(File[] upload) { this .uploads = upload; }
public String[] getUploadFileName() { return this .uploadFileNames; }
public void setUploadFileName(String[] uploadFileName) { this .uploadFileNames = uploadFileName; }
public String[] getUploadContentType() { return this .uploadContentTypes; }
public void setUploadContentType(String[] uploadContentType) { this .uploadContentTypes = uploadContentType; }
清单15 多文件上传数组绑定Action代码片段
如果你想绑定到列表,则应类似:
private List < File > uploads = new ArrayList < File > ();
private List < String > uploadFileNames = new ArrayList < String > ();
private List < String > uploadContentTypes = new ArrayList < String > ();
public List < File > getUpload() {
return this .uplo
|