本文同步于个人Github博客:https://github.com/johnnian/Blog/issues/1,欢迎留言。
Struts2文件下载的相关配置如下:
Struts.xml 配置
<package name="defaultPackage" extends="struts-default">
<!--配置下载Action入口-->
<action name="download" class="com.johnnian.DownloadAction" >
<!--stream 是文件下载的时候专用的-->
<result name="success" type="stream">
<!--文件下载的类型-->
<param name="contentType">${contentType}</param>
<!--文件下载方式分为:-->
<param name="contentDisposition">inline;filename="${filename}"</param>
<!--文件下载入口-->
<param name="inputName">testDownload</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
相关说明:
1、 contentType:
下载文件的类型,客户端向Tomcat请求静态资源的时候,Tomcat会自动在 Response Head 里面添加 “Content-Type” 属性,具体的属性列表配置,参考Tomcat下的 web.xml.
2、 contentDisposition:
这个属性配置下载文件的文件名等属性,其中文件类型划分为inline、attachment两种:
- inline:浏览器尝试直接打开文件
- atachment:浏览器直接下载为附件
这个差别还是有的,比如想要让下载的文件直接在浏览器打开,就需要设置成“inline”
3、 inputName:
配置下载请求的执行方法,例如,上述配置成 “testDownload”, 则在Action类中就需要实现 “getTestDownload” 方法。
4、配置文件中的 ${contentType}
, {filename}
, 需要在实现的接口上定义对应的属性,只要设置好其属性,就可以了~
Java后台
public class TicketDownloadAction extends ActionSupport {
private String testParam;
private String filename;//文件名
private String contentType;//文件类型
/**
* 下载处理方法:
*/
public InputStream getTestDownload() {
// 直接获取参数
String params = getTestParam();
String path = "/Users/Johnnian/tmp/123.png";
this.setFilename("123.png");
this.setContentType("image/png");
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//可以应答任何继承 InputStream 的类实例
return inputStream;
}
//---------------------------------
// Gettter & Setter
//---------------------------------
public String getTestParam() {
return testParam;
}
public void setTestParam(String testParam) {
this.testParam = testParam;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
说明:
- Struts2中的参数是自动注入的,只需要get对应的属性就可以获取
- 需要实现“Struts.xml”中inputName对应的入口,应答一个InputStream文件流即可
Web前端
<a href="http://127.0.0.1:8080/posbox/downloadTicket.jhtml?testParam=12345678"> 点击下载 </a>
可以直接在 <a>
、<img>
等标签中直接使用.
网友评论