1. 在某些应用程序里, 可能需要动态地把一个文件发送到用户的浏览器中, 而这个文件的名字和存放位置在编程时是无法预知的
2. Struts 专门为文件下载提供了一种 Stream 结果类型. 在使用一个 Stream 结果时, 不必准备一个 JSP 页面.
即,struts2中使用type="stream" 的result进行下载即可。
3.使用细节参看struts-2.3.15.3/docs/WW/docs/stream-result.html文档。
4. 可以为streamd的result设置如下的参数值:
4.1 contentType:被下载的文件的 MIME 类型。默认值为 text/plain
4.2 contentLength:被下载的文件的大小,以字节为单位
4.3 contentDisposition: 可以设置下载文件名的ContentDispositon 响应头,默认值为 inline,
通常设置为如下格式: attachment;filename="document.pdf".
4.4 inputName:Action 中提供的文件的输入流。默认值为inputStream
4.5 bufferSize:文件下载时缓冲区的大小。默认值为 1024
4.6 allowCaching :文件下载时是否允许使用缓存。默认值为 true
4.7 contentCharSet:文件下载时的字符编码。
5. 以上的参数可以在Action中以getter方法的方式提供。
6. 下载文件例子。
Action类 :TestDownload.java
package com.lishenhuan.download;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class TestDownload extends ActionSupport{
private String contentType;
private String contentDisposition;
private InputStream inputStream;
private long contentLength;
@Override
public String execute() throws Exception {
//确定各个变量的值
contentType="text/html"; //准备下载的文件类型
contentDisposition="attachment;filename=lishenhuan.html"; //下载文件后的重命名
ServletContext servletContext = ServletActionContext.getServletContext();
String filename = servletContext.getRealPath("/file/warning.htm");
inputStream = new FileInputStream(filename);
contentLength = inputStream.available();
return super.execute();
}
public String getContentType() {
return contentType;
}
public String getContentDisposition() {
return contentDisposition;
}
public InputStream getInputStream() {
return inputStream;
}
public long getContentLength() {
return contentLength;
}
}
struts.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="testUser" extends="struts-default">
<action name="testDownload" class="com.lishenhuan.download.TestDownload">
<result type="stream">
<param name="bufferSize">2048</param>
</result>
</action>
</package>
</struts>