Struts2 逐步成长:(二) 文件上传

Struts2 上传文件利用的是 : FileUploadInterceptor

利用MyEclipse JAVADOC 查看 FileUploadInterceptor的JAVADOC

打开Myeclipse JAVADOC VIEW 方法:

再CTRL+SHIFT+T 定位到 我们需要的 FileUploadIntercptor,于是就会出现它的帮助文档了~


upload.jsp:

            根据文档的提示我们先作出上传文件用的JSP页面的提交表单

          

<s:debug></s:debug>
  	    <s:form action="testUpload" method="post" enctype="multipart/form-data">
  	    	<s:file name="upload" label="File"></s:file> 
 	        <s:submit/>
            </s:form>
Tips: name中的值我们稍后会在action中用到!!!!!!!!!!!!

UploadAction.java:

            帮助文档告诉我们,ACTION中有这3个属性

           

    private File upload;
    private String uploadContentType;
    private String uploadFileName;

再实现相应的SETTER,GETTER,execute()方法,上传ACTION就算完了.~

Tips:注意看这3个变量,它们是由JSP中file的name属性来设置的,帮助文档充分的说明了这一点,如果变量名写错,会导致获取的值是null~


Struts.xml:

通过javadoc,我们知道怎样设置出错时的国际化资源文件

so:

   

<!-- i18n.properties 文件内容 -->

struts.messages.error.uploading=a general error that occurs when the file could not be uploaded 

struts.messages.error.file.too.large=occurs when the uploaded file is too large 

struts.messages.error.content.type.not.allowed=occurs when the uploaded file does not match the expected content types specified 

struts.messages.error.file.extension.not.allowed=occurs when the uploaded file does not match the expected file extensions specified 

<!-- struts.xml 配置国际化 -->
<constant name="struts.custom.i18n.resources" value="i18n"></constant>

通过JAVADOC,我们知道怎么限制上传文件:

	<interceptors>
		<interceptor-stack name="uploadintersepetor">
			<interceptor-ref name="defaultStack">
				<param name="fileUpload.maximumSize">2097152</param>
				<param name="fileUpload.allowedTypes ">text/html</param>
				<param name="fileUpload.allowedExtensions ">html</param>				
			</interceptor-ref>
		</interceptor-stack>
	</interceptors>
	
	<!-- 使用刚才配置的拦截器 -->
	<default-interceptor-ref name="uploadintersepetor"></default-interceptor-ref>

设置ACTION:

	<!-- upload action -->
	<action name="testUpload" class="com.upload.app.UploadAction">
		<result>/uploadSuc.jsp</result>
		<result name="input">/upload.jsp</result>
	</action>

这样整个功能就写好了~~不过我们没有保存文件,只需用IO流保存就行了!


多文件上传:

变量类型设置为List<>:

    private List<File> upload;
    private List<String> uploadContentType;
    private List<String> uploadFileName;

JSP页面中file的name值相同

<s:debug></s:debug>
  	    <s:form action="testUpload" method="post" enctype="multipart/form-data">
  	    	<s:file name="upload" label="File"></s:file>
  	    	<s:file name="upload" label="File"></s:file>
  	    	<s:file name="upload" label="File"></s:file> 
  	    	<s:submit/>
  	    </s:form>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值