1、错误方法:
直接在ajax中传path到后台,下载后放在response中返回,会出现错误,因为ajax只接受字符串等类型,不能解析头文件
2、解决:
2.1方案一
可以直接将前台改成超链接,在href中跳转到controller,可以执行下载(但是这个方法不方便传参),自己尝试在href中传path没有成功
2.2方案二
又要传参,又要放在头文件中返回怎么处理呢?
查阅网上各博客,都说用 window.location.href =代替ajax,但没有具体实施方案
下面给出自己尝试后成功的例子(思路:先用ajax将参数传到后台,存在session中,在ajax请求成功后,使用window.location.href跳转到执行下载的controller)
前台:
$(".fa-download").click(function() {
var path = $(this).attr("value");
$.ajax({
url: "mail/preDownLoad",
type: "post",
dataType: "text",
data:{"path":path},
success: function (data) {
alert("成功")
if (!isEmpty(path)) {
window.location.href = "mail/downLoad";
} else {
alert("附件路径丢失")
}
},
error: function (err) {
alert("下载失败")
/* $.dialog.alert("下载失败"); */
}
});
});
后台:
过渡的controller
@RequestMapping("/preDownLoad")
public String preDownLoad(String path, HttpSession session) {
session.setAttribute("path", path);
return "message/informationDetails";
}
执行下载的controller
@RequestMapping("/downLoad")
public void downLoad(HttpSession session, HttpServletResponse response) {
String path = (String) session.getAttribute("path");
// path是指欲下载的文件的路径
File file = new File(path);
// 取得文件名
String filename = file.getName();
// 以流的形式下载文件
InputStream fis;
try {
fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-disposition", "attachment;filename=" + new String(filename.getBytes()));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setContentType("application/x-msdownload");
toClient.write(buffer);
toClient.flush();
toClient.close();
System.out.println("下载成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}