在线等!! java txt导出的问题
web工程,页面通过ajax请求调用action中的writeToTxt() ,控制台也没有抛异常,为什么不弹出下载框呢?
public void writeToTxt()
{
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=aaa.txt");
ServletOutputStream os = null;
BufferedOutputStream bos = null;
StringBuffer sb = new StringBuffer();
String enter = "\r\n";
try
{
os = response.getOutputStream();
bos = new BufferedOutputStream(os);
sb.append("abc");
bos.write(sb.toString().getBytes("UTF-8"));
bos.flush();
bos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
------解决方案--------------------刚才这个链接就是实现你说的效果的呀。
1:你首先要把你说的“abc”写到aaa.txt里。
String rootPath = request.getSession().getServletContext().getRealPath("/");
File file = new File(rootPath+"/" + "aaa.txt"); //要下载的文件绝对路径
OutputStream ous = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = "abc".getBytes();
ous.write(buffer);
ous.close();
2: 把"aaa.txt"输出给客户端。
HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String("aaa.txt".getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream ous = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
ous.write(buffer);
ous.flush();
ous.close();