版权声明:博客知识产权来源命运的信徒,切勿侵权 https://blog.csdn.net/qq_37591637/article/details/85088190
Struts2使用type="stream"的result就可以了
contentType:结果类型
contentLength:下载的文件的长度
contentDisposition:设定的响应头,文件的下载类型
inputName:指定文件输入流的getter定义的属性的名字,默认inputstream
前4个是可以动态获取的,后面是静态的
bufferSize:缓存的大小1024
allowCaching:是否允许的使用缓存
contentCharSet:指定下载的字符集
以上采纳数可以在Action中以getter方法的方式获取
Demo如下
jsp页面
<a href="upload.do">点击下载源文件</a>
Struts2.xml文件配置如下
<action name="upload" class="cn.com.app.Upload" method="execute">
<result type="stream" name="success">
<param name="bufferSize">2048</param>
</result>
<result name="input">/index.jsp</result>
</action>
Action类如下
package cn.com.app;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Upload extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private String contentType;
private long contentLength;
private String contentDisposition;
private InputStream InputStream;
public String getContentType() {
return contentType;
}
public long getContentLength() {
return contentLength;
}
public String getContentDisposition() {
return contentDisposition;
}
public InputStream getInputStream() {
return InputStream;
}
@Override
public String execute() {
// TODO Auto-generated method stub
// 确认各个成员对象的值
contentType = "text/html";
contentDisposition = "attachment;filename=a.html";
// 获取文件的路径
ServletContext sv = ServletActionContext.getServletContext();
String fileName = sv.getRealPath("/files/a.html");
// 读取文件
try {
InputStream = new FileInputStream(fileName);
System.out.println("路径:" + InputStream);
// 文件的长度
contentLength = InputStream.available();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
}
前提是WebRoot下面有文件,文件是存在的
成功效果如下