读书人

! java txt导出的有关问题

发布时间: 2013-04-22 16:01:35 作者: rapoo

在线等!! 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();



引用:
引用:看看这个吧:
http://blog.csdn.net/maosijunzi/article/details/7844292
我是要导出数据,比如范例代码中的‘abc'导入到txt中,点击页面按钮时,弹出个下载/打开对话框的

[解决办法]
不需要先生成文件的,你的代码我试过了,直接点击链接是可以下载的,但是用ajax请求就不行。
[解决办法]
下载文件不用ajax直接提交页面也不会跳转的。
[解决办法]
下载当然不能用ajax了 你后台输出的数据 都被ajax的 success:function(data){} 里面的data接收 怎么输出到页面?用普通的跳转 或者用 <a href="下载的actin"><a>标签

读书人网 >J2SE开发

热点推荐