java中struts2实现简单的文件上传与下载
一、Struts2文件上传
Struts2的文件上传实现非常简单,只需要简单几步就可完成;
注意:
(1)文件上传的struts2标签为:<s:filename=""label="上传"/>
(2)文件上传的前提是表单属性method="post"enctype="multipart/form-data";
(3)web应用中必须包含common-fileupload.jar和common-io.jar,因为struts2默认上传解析器使用的是jakarta;
(4)可以在struts.xml中配置最大允许上传的文件大小:<constantname="struts.multipart.maxSize"value="....."/>,默认为2M;
1.普通文件上传
实现规则:
(1)在JSP中设定表单控件<s:filename="upload"label="上传"/>
(2)在Action中定义属性:
privateFileupload; //包含文件内容
privateStringuploadFileName; //上传文件的名称;
privateStringuploadContentType; //上传文件的MIME类型;
这些属性都会随着文件的上传自动赋值;
(3)在execute()中完成写入磁盘功能;
代码示例:
Upload01Action.java
packageorg.upload.action; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileOutputStream; importorg.apache.struts2.ServletActionContext; importcom.opensymphony.xwork2.ActionSupport; publicclassUpload01ActionextendsActionSupport{ privateFileupload; privateStringuploadFileName; privateStringuploadContentType; privateStringname; publicStringexecute()throwsException{ Stringpath=ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload"); Stringfilename=path+File.separator+name; FileInputStreamin=newFileInputStream(upload); FileOutputStreamout=newFileOutputStream(filename); byte[]b=newbyte[1024]; intlen=0; while((len=in.read(b))>0){ out.write(b,0,len); } out.close(); returnSUCCESS; } publicFilegetUpload(){ returnupload; } publicvoidsetUpload(Fileupload){ this.upload=upload; } publicStringgetUploadFileName(){ returnuploadFileName; } publicvoidsetUploadFileName(StringuploadFileName){ this.uploadFileName=uploadFileName; } publicStringgetUploadContentType(){ returnuploadContentType; } publicvoidsetUploadContentType(StringuploadContentType){ this.uploadContentType=uploadContentType; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } }
struts.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEstrutsPUBLIC "-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constantname="struts.devMode"value="true"/> <constantname="struts.custom.i18n.resources"value="message"></constant> <packagename="default"namespace="/"extends="struts-default"> <actionname="upload0*"class="org.upload.action.Upload0{1}Action"> <paramname="name">1.jpg</param> <result>/{1}.jsp</result> </action> </package> </struts>
1.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%> <%@taglibprefix="s"uri="/struts-tags"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <title>MyJSP'1.jsp'startingpage</title> </head> <body> <s:formaction="upload01"method="post"enctype="multipart/form-data"> <s:filename="upload"label="上传"></s:file> <s:submitvalue="上传"></s:submit> </s:form> </body> </html>
2.利用拦截器进行过滤
手动实现过滤的方式非常简单,就是利用输入校验的方式进行过滤,即在validate()中进行过滤;
而这里要讲的拦截器方式是很好的方式,只需要在配置文件中配置,灵活性很好,能够限制文件的类型、文件的大小;如果上传的文件不符合要求,则返回input逻辑视图;
配置拦截器步骤:
(1)文件上传的拦截器为fileUpload;
(2)需要给定参数allowedTypes、maximumSize;
(3)在fileUpload拦截器后,需要添加<interceptor-refname="defaultStack"/>
代码示例:
由于通过拦截器进行过滤只需要配置struts.xml,因此这里只给出struts.xml的配置
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEstrutsPUBLIC "-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constantname="struts.devMode"value="true"/> <constantname="struts.custom.i18n.resources"value="message"></constant> <packagename="default"namespace="/"extends="struts-default"> <actionname="upload0*"class="org.upload.action.Upload0{1}Action"> <interceptor-refname="fileUpload"> <paramname="allowedTypes">image/jpeg,image/gif</param> <paramname="maximumSize">1024*1024</param> </interceptor-ref> <interceptor-refname="defaultStack"></interceptor-ref> <paramname="name">1.jpg</param> <result>/{1}.jsp</result> <resultname="input">/{1}.jsp</result> </action> </package> </struts>
我们还需要配置文件上传失败后的错误提示信息,我们需要在全局国际化资源文件中配置:
struts.messages.error.content.type.not.allowed=文件类型不匹配 struts.messages.error.file.too.large=文件太大
二、Struts2文件下载
我们在学习Servlet和HTTP协议时已经可以实现文件下载,即写content-disposition头即可,struts2的实现原理也是这个,但是提供了更好的封装性;
struts2的stream结果类型专门用于实现文件下载;
(1)struts.xml中配置stream结果类型,并配置contentType、contentDisposition、bufferSize参数即可,模板:
<actionname="download"class=""> <resulttype="stream"name="success"> <paramname="contentType"></param> <paramname="contentDisposition">attachment;filename=""</param> <paramname="bufferSize">4096</param> </result> </action>
(2)在Action中创建publicInputStreamgetInputStream()throwsException;方法,此方法用于获得下载文件的输入流;
DownloadAction.java
packageorg.download.action; importjava.io.InputStream; importorg.apache.struts2.ServletActionContext; importcom.opensymphony.xwork2.ActionSupport; publicclassDownloadActionextendsActionSupport{ publicInputStreamgetInputStream()throwsException{ returnServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/upload/1.jpg"); } publicStringexecute()throwsException{ returnSUCCESS; } }
struts.xml
<actionname="download"class="org.download.action.DownloadAction"> <resulttype="stream"name="success"> <paramname="contentType">image/jpeg</param> <paramname="contentDisposition">attachment;filename="1.jpg"</param> <paramname="bufferSize">4096</param> </result> </action>
就可以完成下载。
java中struts2文件上传下载的实现就为大家介绍到这里,谢谢大家的阅读。