27.struts2_文件的下载

来源:互联网 发布:js转换时间格式的方法 编辑:程序博客网 时间:2024/06/11 05:42


Struts2专门为文件下载提供了一种Stream结果类型,在使用Stream结果时,不必准备一个JSP页面。

可为result 设定如下参数:

contentType: 结果类型

contentLength:下载长度

contentDisposition:设定相应头,是一个文件下载类型。一般取值格式为: attachment;filename=“document.pdf”.

inputName: 指定文件输入流的 getter定义的属性的名字,默认为 inputStream

bufferSize:缓存的大小 默认为1024

allowCaching:是否允许使用缓存

contentCharSet:指定下载的字符集

以上参数也可以在Aciton中以getter方法的方式提供。


public class testDownloadAction  extends ActionSupport{/** *  */private static final long serialVersionUID = 1L;private String contentType;private long contentLength;private String contentDisposition;private InputStream inputStream;//提供一个输入流public InputStream getInputStream() {return inputStream;}public String getContentType() {return contentType;}public long getContentLength() {return contentLength;}public void setContentLength(long contentLength) {this.contentLength = contentLength;}public String getContentDisposition() {return contentDisposition;}public void setContentDisposition(String contentDisposition) {this.contentDisposition = contentDisposition;}public void setContentType(String contentType) {this.contentType = contentType;}@Overridepublic String execute() throws Exception {//确定各个成员变量的值contentType="text/html";contentDisposition=new String("attachment;filename='綿谷の.html'".getBytes(), "ISO8859-1"); //有中文需要转码,不然下载不识别System.out.println("------"+contentDisposition);ServletContext sac=ServletActionContext.getServletContext();String fileName=sac.getRealPath("/files/知乎.html");inputStream=new FileInputStream(fileName);contentLength=inputStream.available();return super.execute();}}

struts.xml部分内容

<action name="testDownload" class="com.hcx.app.testDownloadAction"><result name="success" type="stream" ><param name="bufferSize" >2048</param></result></action>


原创粉丝点击