文件下载
在struts2中如何实现文件下载
1.添加一个文件下载的action类
public class DownloadAction{
private InputStream logoStream;
public InputStream getLogoStream(){
try{
this.fileName = brand.getLogoUrl();
//获取被下载的文件的绝对路径
String filePath = ServletActionContext.getRequest().getServletContext().getRealPath(brand.getLogoUrl());
System.out.println(filePath);
//读取被下载的文件
logoStream = new FileInputStream(filePath);
return logoStream;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
}
2.在该类中添加一个action方法,返回success
public class DownloadAction{
public String download(){
return "success";
}
}
3.在struts.xml中配置该action,并且result的结果类型为stream
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
</result>
</action>
4.在result中设置参数inputName,该参数的值必须为action类中的一个数据类型为InputStream的属性。
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
<param name="inputName">logoStream</param>
</result>
</action>
5.控制下载文件的文件名称:在result中添加参数:contentDisposition
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
<param name="inputName">logoStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
</result>
</action>
注意:${fileName} 中的fileName为action类中的属性
6.控制文件的类型:在result中添加参数:contentType
contentType:
word : application/msword
excel : application/vnd.ms-excel
ppt : application/vnd.ms-powerpoint
html : text/html
文本文件 : text/plain
可执行文件 : application/octet-stream
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
<param name="inputName">logoStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="contentType">application/octet-stream</param>
</result>
</action>