内容简介:Struts2 文件下载
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>
等标签中直接使用.
以上所述就是小编给大家介绍的《Struts2 文件下载》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Netty接收HTTP文件上传及文件下载
- struts实战--文件下载
- 前端文件下载通识篇
- Android原生下载(下篇)多文件下载+多线程下载
- jsp文件下载功能实现代码
- 使用selenium实现批量文件下载
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Agile Web Development with Rails, Third Edition
Sam Ruby、Dave Thomas、David Heinemeier Hansson / Pragmatic Bookshelf / 2009-03-17 / USD 43.95
Rails just keeps on changing. Rails 2, released in 2008, brings hundreds of improvements, including new support for RESTful applications, new generator options, and so on. And, as importantly, we’ve a......一起来看看 《Agile Web Development with Rails, Third Edition》 这本书的介绍吧!