java-web调用后台下载方法

后台下载指定文件必定会用到流, 

无论使用poi还是使用jxl导出excel都需要用到流
一种是outputstrean,另一种fileoutputstream
第一种:如果想要弹出保存的提示框必须加入下列三句
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+filename);
response.setCharacterEncoding("utf-8");
OutputStream os=response.getOutputStream();
在使用第一种的时候,我用的ajax请求。导致excel无法导出,最后我直接请求可以导出
原因是:ajax也用到了response.getWriter()方法 要将 数据结果回传,这里 我虽然 放弃了 回传的写入流writer 参数, 但是ajax还是会默认的去掉用,把流已经占用了,当然返回不了任何东西了。
第二种:
action中使用
FileOutputStream fos=new FileOutputStream(file);
此时可以使用ajax请求,在导出成功后返回文件路径,在页面中使用window.open(path);即可打开导出的excel文件

如果某些情况下,必须用到通过js的方式调用后台下载方法,可以借鉴第二种方式,在js中生成一个action方法:

  function showfile(fileId)  {

    //定义一个form表单,通过form表单来发送请求var form = $("<form>");

//设置表单状态为不显示
form.attr("style", "display:none");
//method属性设置请求类型为post
form.attr("method", "post");
//action属性设置请求路径,
//请求类型是post时,路径后面跟参数的方式不可用
//可以通过表单中的input来传递参数
form.attr("action", path + "/dbsx-dbsx-fileDownload.do");
$("body").append(form);//将表单放置在web中
//在表单中添加input标签来传递参数
//如有多个参数可添加多个input标签
var inputcs = $("<input>");
inputcs.attr("type", "hidden");//设置为隐藏域
inputcs.attr("name", "articleFile.id");//设置参数名称
inputcs.attr("value", fileId);//设置参数值
form.append(inputcs);//添加到表单中
form.submit();//表单提交

}

原文地址:https://www.cnblogs.com/salmonLeeson/p/11253870.html