快速业务通道

在Struts 2中实现文件上传 - 编程入门网

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-06-18
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。

发布运行应用程序,出错时,页面如下图所示:

在Struts 2中实现文件上传 - 编程入门网

清单12 出错提示页面

上面的出错提示是Struts 2默认的,大多数情况下,我们都需要自定义和国际化这些信息。通过在全局的国际资源文件中加入“struts.messages.error.content.type.not.allowed=The file you uploaded is not a image”,可以实现以上提及的需求。对此有疑问的朋友可以参考我之前的文章《在Struts 2.0中国际化(i18n)您的应用程序》。

实现之后的出错页面如下图所示:

在Struts 2中实现文件上传 - 编程入门网

清单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

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号