java中struts2实现文件上传下载功能
先谈一谈struts2实现文件的上传和下载实例实现的原理:
Struts2是通过CommonsFileUpload文件上传。
CommonsFileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。
具体实现:
一、创建index.jsp页面
<body> <s:formaction="upload"method="post"theme="simple"enctype="multipart/form-data"> <tablealign="center"width="50%"border="1"> <tr> <td>选择上传文件</td> <tdid="more"> <s:filename="file"></s:file> <inputtype="button"value="AddMore.."onclick="addMore()"> </td> </tr> <tr> <td><s:submittype="button"value="submit"onclick="returncheckf()"/></td> <td><s:resetvalue="reset"></s:reset></td> </tr> </table> <tablealign="center"width="50%"border="1"> <tr> <td>测试.txt</td> <td> <ahref="<s:urlvalue='download.action'><s:paramname='fileName'>测试.txt</s:param></s:url>">下载</a> </td> </tr> </table> </s:form> </body>
创建result.jsp页面
<body> <s:form> <divstyle="border:1pxsolidblack">成功上传的文件:<br> <ulstyle="list-style-type:decimal"> <s:iteratorvalue="#request.fileName"id="file"status="status"> <li><s:property/></li> </s:iterator> </ul> </div> </s:form> </body>
当然别忘了在每个页面上都添加上struts2标签引用<%@taglibprefix="s"uri="/struts-tags"%>
二、创建updown.js文件,在index.jsp中引用
functioncheckf(){
varfiles=document.getElementsByName("file");
if(files[0].value.length!=0){
returntrue;
}else{
alert("请选择文件");
returnfalse;
}
}
functionaddMore()
{
vartd=document.getElementById("more");
varbr=document.createElement("br");
varinput=document.createElement("input");
varbutton=document.createElement("input");
input.type="file";
input.name="file";
button.type="button";
button.value="Remove";
button.onclick=function()
{
td.removeChild(br);
td.removeChild(input);
td.removeChild(button);
}
td.appendChild(br);
td.appendChild(input);
td.appendChild(button);
}
三、创建upDownloadAction.java
packagecom.action;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.UnsupportedEncodingException;
importjava.util.List;
importjavax.servlet.http.HttpServletRequest;
importcom.opensymphony.xwork2.ActionSupport;
importorg.apache.struts2.ServletActionContext;
publicclassUpDownloadActionextendsActionSupport{
privatestaticfinallongserialVersionUID=1L;
privateList<File>file;//对应jsp中file标签
privateList<String>fileFileName;//
privateList<String>fileContentType;//
privateStringfileName;//获得jsp中pram参数
@SuppressWarnings("deprecation")
//文件上传
publicStringuploadFiile()throwsException{
Stringroot=ServletActionContext.getServletContext().getRealPath(
"/upload");//上传路径
System.out.println(root);
InputStreaminputStream;
FiledestFile;
OutputStreamos;
for(inti=0;i<file.size();i++){
inputStream=newFileInputStream(file.get(i));
destFile=newFile(root,this.getFileFileName().get(i));
os=newFileOutputStream(destFile);
byte[]buffer=newbyte[400];
intlength=0;
while((length=inputStream.read(buffer))>0){
os.write(buffer,0,length);
}
inputStream.close();
os.close();
}
HttpServletRequestrequest=ServletActionContext.getRequest();
request.setAttribute("fileName",fileFileName);
returnSUCCESS;
}
//文件下载
publicInputStreamgetDownloadFile()throwsFileNotFoundException,
UnsupportedEncodingException{
System.out.println(getFileName());
//如果下载文件名为中文,进行字符编码转换
ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="
+java.net.URLEncoder.encode(fileName,"UTF-8"));
InputStreaminputStream=newFileInputStream("F:/"//使用绝对路径,从该路径下载“测试.txt"文件
+this.getFileName());
System.out.println(inputStream);
returninputStream;
}
//下载
publicStringdownloadFile()throwsException{
returnSUCCESS;
}
publicStringgetFileName()throwsUnsupportedEncodingException{
returnfileName;
}
publicvoidsetFileName(StringfileName)
throwsUnsupportedEncodingException{
this.fileName=newString(fileName.getBytes("ISO8859-1"),"utf-8");
}
}
注:属性的get和set方法已省略。
四、最后是配置文件
1、web.xml配置
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2、struts.xml配置
<struts>
<constantname="struts.i18n.encoding"value="utf-8"></constant>
<constantname="struts.multipart.saveDir"value="f:\"></constant>
<packagename="struts2"extends="struts-default">
<actionname="upload"class="com.action.UpDownloadAction"method="uploadFiile">
<resultname="success">/jsp/result.jsp</result>
<interceptor-refname="fileUpload">
<!--maximumSize(可选)-这个拦截器允许的上传到action中的文件最大长度(以byte为单位).
注意这个参数和在webwork.properties中定义的属性没有关系,默认2MB-->
<paramname="maximumSize">409600</param>
<!--allowedTypes(可选)-以逗号分割的contentType类型列表(例如text/html),
这些列表是这个拦截器允许的可以传到action中的contentType.如果没有指定就是允许任何上传类型.-->
<paramname="allowedTypes">
text/plain
</param>
</interceptor-ref>
<interceptor-refname="defaultStack"></interceptor-ref>
</action>
<actionname="download"class="com.action.UpDownloadAction"method="downloadFile">
<resultname="success"type="stream">
<!--指定文件下载类型application/octet-stream默认值可以下载所有类型-->
<paramname="contentType">
application/txt;
</param>
<!--指定下载的文件名和显示方式,但注意中文名的乱码问题,解决办法是:进行编码处理-->
<!--contentDisposition是文件下载的处理方式,包括内联(inline)和附件(attachment),
默认是inline,使用附件时这样配置:attachment;filename="文件名"。-->
<paramname="contentDisposition">
attachment;filename="${fileName}"
</param>
<!--由getDownloadFile()方法获得inputStream-->
<paramname="inputName">downloadFile</param>
<!--指定下载文件的缓存大小-->
<paramname="bufferSize">2048</param>
</result>
</action>
</package>
</struts>
一个简单的Struts2多文件上传和单文件下载就实现了。
以上就是本文的全部内容,希望对大家的学习有所帮助。