Struts2下多文件的上传与下载Word下载.docx
- 文档编号:19713388
- 上传时间:2023-01-09
- 格式:DOCX
- 页数:18
- 大小:198.61KB
Struts2下多文件的上传与下载Word下载.docx
《Struts2下多文件的上传与下载Word下载.docx》由会员分享,可在线阅读,更多相关《Struts2下多文件的上传与下载Word下载.docx(18页珍藏版)》请在冰豆网上搜索。
文件下载很少的,看似简单,实则不然
3)
文件下载一般都是单文件或者固定的文件,并没有(很少)实现随意文件的下载的例子
最近也在研究一下文件的上传和下载,在整合网上、浪曦风中叶老师和自己的学习的思想,写了这个工程,提供给大家参考,所以的代码终在IE、FireFox、Chrome测试通过。
需求
1.能够对多个文件进行上传(可以选择上传文件个数,也即上传文件个数不定)
2.能够对上传路径进行配置文件(upload.properties)指定,使用了一些类似单例模式的静态代码块
3.对配置文件中的路径可以进行动态读取(不重启服务器)
4.Struts2进行下载处理,能对上传的所有文件进行下载(多个)
5.文件保存的名称UUID生成,不过显示并下载的名称都是原文件名称
(人性化,通过UploadFiles处理)
环境
最新的Struts2:
struts-2.1.8、MyEclipse、Tomcat、IE、FireFox、Chrome
目录结构
重要文件的看点
web.xml
…
<
filter>
filter-name>
struts2<
/filter-name>
filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter<
/filter-class>
/filter>
在web.xml中使用了最新的Struts2的中央处理器类org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter,而不再是以前的org.apache.struts2.dispatcher.FilterDispatcher,FilterDispatcher在新版本Struts2中已经标注为过时了,请大家尽量使用最新的filter。
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.i18n.encoding"
value="
utf8"
/>
packagename="
file"
namespace="
/"
extends="
struts-default"
<
actionname="
showUpload"
<
result>
/upload.jsp<
/result>
/action>
upload"
class="
org.usc.file.UploadAction"
resultname="
input"
--<
success"
/upload_success.jsp<
-->
/download.jsp<
interceptor-refname="
fileUpload"
--大家可以设置成自己的配置,想文件类型和大小等限制-->
--<
paramname="
maximumSize"
2097152<
/param>
单位是字节2M(2097152B)-->
allowedTypes"
image/bmp,image/x-png,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg<
---->
--容许文件类型为doc,ppt,xls,pdf,txt,java-->
/interceptor-ref>
defaultStack"
download"
org.usc.file.DownloadAction"
type="
stream"
<
contentDisposition"
attachment;
filename="
${fileName}"
inputName"
downloadFile<
/package>
/struts>
就是文件上传和下载的一些Struts2配置,注意上传的时候,请引入
,
下载的配置中注意:
其他的配置解释网上很多,不懂的可以先google学习一下。
UploadAction
在此文件中请注意文件数组的使用,因为是多文件
packageorg.usc.file;
importjava.io.File;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.UUID;
importmons.io.FileUtils;
importorg.apache.struts2.ServletActionContext;
importorg.usc.utils.UploadConfigurationRead;
importcom.opensymphony.xwork2.ActionSupport;
/**
*多文件上传类
*
*@authorMZ
*@Time2009-11-24下午09:
26:
44
*/
publicclassUploadActionextendsActionSupport
{
/**
privatestaticfinallongserialVersionUID=1L;
privateFile[]upload;
//实际上传文件
privateString[]uploadContentType;
//文件的内容类型
privateString[]uploadFileName;
//上传文件名
privateList<
UploadFiles>
uploadFiles=newArrayList<
();
publicStringexecute()throwsException
{
try
{
StringtargetDirectory=ServletActionContext.getServletContext()
.getRealPath("
+UploadConfigurationRead.getInstance().getConfigItem("
uploadFilePath"
).trim());
//获得路径
for(inti=0;
i<
upload.length;
i++)
{
StringfileName=uploadFileName[i];
//上传的文件名
Stringtype=uploadContentType[i];
//文件类型
StringrealName=UUID.randomUUID().toString()+getExt(fileName);
//保存的文件名称,使用UUID+后缀进行保存
Filetarget=newFile(targetDirectory,realName);
FileUtils.copyFile(upload[i],target);
//上传至服务器的目录,一般都这样操作,
//在把路径写入数据库即可
UploadFilesuf=newUploadFiles();
//创建文件
uf.setUploadContentType(type);
uf.setUploadFileName(fileName);
uf.setUploadRealName(realName);
uploadFiles.add(uf);
//添加到需要下载文件的List集合中
}
ServletActionContext.getRequest().setAttribute("
uploadFiles"
uploadFiles);
}catch(Exceptione)
e.printStackTrace();
addActionError(e.getMessage());
returnINPUT;
}
returnSUCCESS;
}
publicFile[]getUpload()
returnupload;
publicvoidsetUpload(File[]upload)
this.upload=upload;
publicString[]getUploadContentType()
returnuploadContentType;
publicvoidsetUploadContentType(String[]uploadContentType)
this.uploadContentType=uploadContentType;
publicString[]getUploadFileName()
returnuploadFileName;
publicvoidsetUploadFileName(String[]uploadFileName)
this.uploadFileName=uploadFileName;
publicstaticStringgetExt(StringfileName)
returnfileName.substring(fileName.lastIndexOf("
."
));
}
DownloadAction
在此文件中要注意publicInputStreamgetDownloadFile()的名称在Struts2配置文件配置,返回的是一个InputStream类型的对象。
importjava.io.InputStream;
importjava.io.UnsupportedEncodingException;
publicclassDownloadActionextendsActionSupport
privatestaticfinallongserialVersionUID=6329383258366253255L;
privateStringfileName;
privateStringfileRealName;
publicvoidsetFileName()
//得到请求下载的文件名
Stringfname=ServletActionContext.getRequest().getParameter("
name"
);
Stringfrealname=ServletActionContext.getRequest().getParameter("
realname"
/*
*对fname参数进行UTF-8解码,注意:
实际进行UTF-8解码时会使用本地编码,本机为GBK。
*这里使用request.setCharacterEncoding解码无效.
*只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件
*/
fname=newString(fname.getBytes("
ISO-8859-1"
),"
frealname=newString(frealname.getBytes("
this.fileName=fname;
this.fileRealName=frealname;
//System.out.println(fileName);
//System.out.println(fileRealName);
/*
*@getFileName此方法对应的是struts.xml文件中的:
param
*name="
*这个属性设置的是下载工具下载文件时显示的文件名,要想正确的显示中文文件名,我们需要对fileName再次编码
*否则中文名文件将出现乱码,或无法下载的情况
publicStringgetFileName()throwsUnsupportedEncodingException
fileRealName=newString(fileRealName.getBytes(),"
returnfileRealName;
*@getDownloadFile此方法对应的是struts.xml文件中的:
返回下载文件的流,可以参看struts2的源码
publicInputStreamgetDownloadFile()
this.setFileName();
returnServletActionContext.getServletContext().getResourceAsStream("
+UploadConfigurationRead.getInstance().getConfigItem("
).trim()+"
+fileName);
@Override
UploadConfigurationRead
动态读取配置文件,借鉴网上的代码
packageorg.usc.utils;
importjava.io.FileInputStream;
import.URI;
import.URISyntaxException;
importjava.util.Properties;
*动态读取配置文件类
*
*@Time2009-11-24下午08:
25:
22
publicclassUploadConfigurationRead{
*属性文件全名,需要的时候请重新配置PFILE
privatestaticStringPFILE="
upload.properties"
;
*配置文件路径
privateURIuri=null;
*属性文件所对应的属性对象变量
privatelongm_lastModifiedTime=0;
*对应于属性文件的文件对象变量
privateFilem_file=null;
privatePropertiesm_props=null;
*唯一实例
privatestaticUploadConfigurationReadm_instance=newUploadConfigurationRead();
*私有构造函数
*@throwsURISyntaxException
privateUploadConfigurationRead(){
try{
m_lastModifiedTime=getFile().lastModified();
if(m_lastModifiedTime==0){
System.err.println(PFILE+"
filedoesnotexist!
"
m_props=newProperties();
m_props.load(newFileInputStream(getFile()));
}catch(URISyntaxExceptione){
System.err.println(PFILE+"
文件路径不正确"
}catch(Exceptione){
文件读取异常"
*查找ClassPath路径获取文件
*@returnFile对象
privateFilegetFile()throwsURISyntaxException{
URIfileUri=this.getClass().getClassLoader().getResource(PFILE).toURI();
m_file=newFile(fileUri);
returnm_file;
*静态工厂方法
*@return返回ConfigurationRead的单一实例
publicsynchronizedstaticUploadConfigurationReadgetInstance(){
returnm_instance;
*读取一特定的属性项
publicStringgetConfigItem(Stringname,StringdefaultVal){
longnewTime=m_file.lastModified();
//检查属性文件是否被修改
if(newTime==0){
//属性文件不存在
filedoesnotexist!
}else{
filewasdeleted!
returndefaultVal;
}elseif(newTime>
m_lastModifiedTime){
m_props.clear();
try{
m_props.load(newFileInputStream(getFile()));
}catch(Exceptione){
System.err.println("
文件重新读取异常"
e.printStackTrace();
m_lastModifiedTime=newTime;
Stringval=m_props.getProperty(name);
if(val==null){
}else{
returnval;
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Struts2 文件 上传 下载