欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

struts2响应文件 struts2下载txt

程序员文章站 2022-03-09 23:20:21
public class txtAction extends ActionSupport { private String type; @Action(value="getTxt") public String getTxt() { if("txt".equals(type)){ String re ......

public class txtAction extends ActionSupport {

private String type;

@Action(value="getTxt")
public String getTxt() {
if("txt".equals(type)){
String restxt="鲲鹏展翅";

ServletActionContext.getResponse().setContentType("text/plain");

ServletActionContext.getResponse().setCharacterEncoding("gbk");
ServletActionContext.getResponse().setHeader("connection", "close");
ServletActionContext.getResponse().setHeader("Content-Disposition","attachement;filename="+System.currentTimeMillis()+".txt");

try {
InputStream is = new ByteArrayInputStream(restxt.getBytes("UTF-8"));

//通过response获得输出流
OutputStream os=ServletActionContext.getResponse().getOutputStream();
byte[] b=new byte[1024];
int len=0;
while((len=is.read(b))!=-1){
os.write(b, 0, len);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}


public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}

}