1.首先,使用js来下载是不会保存文件到本地的,因为js不会与硬盘交互,基于安全性原则.
参考:https://www.cnblogs.com/nuccch/p/7151228.html
具体原理:
Ajax无法下载文件的原因
浏览器的GET(frame、a)和POST(form)请求具有如下特点:
response会交由浏览器处理
response内容可以为二进制文件、字符串等
Ajax请求具有如下特点:
response会交由Javascript处理
response内容仅可以为字符串
因此,Ajax本身无法触发浏览器的下载功能。
2.在不使用a标签,纯js下解决办法有三种,一种是直接配置tomcat下载,但这种不安全
参考:简单粗暴JavaWeb-第五篇:直接访问HTML、图片
https://blog.csdn.net/yhan_shen/article/details/78555290
又或者一些.exe文件直接可以通过路径下载,是因为服务器配置了Apache文件的local path代理,同时开放了文件下载权限
3.第二种是HTML5 a.download结合blob对象进行下载
4.第三种是内部用js写一个form或者iframe来提交
这里详说第三种:
定义form:
var form=$("<form>");//定义一个form表单
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action","exportData");
var input1=$("<input>");
input1.attr("type","hidden");
input1.attr("name","exportData");
input1.attr("value",(new Date()).getMilliseconds());
$("body").append(form);//将表单放置在web中
form.append(input1);
form.submit();//表单提交
参考:http://www.cnblogs.com/sydeveloper/archive/2013/05/14/3078295.html
iframe:
function download(){
var IFrameRequest=document.createElement("iframe");
IFrameRequest.id="IFrameRequest";
IFrameRequest.src="/test.zip";
IFrameRequest.style.display="none";
document.body.appendChild(IFrameRequest);
}
参考:
https://www.cnblogs.com/voiphudong/p/3284724.html
后台:
public boolean download(String filePath, HttpServletResponse resp) {
logger.debug("-------Start to download file[{}]----------", filePath);
boolean isDownload = false;
try {
File file = new File(filePath);
String fileName = file.getName();
InputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[in.available()];
in.read(buffer);
in.close();
resp.reset();
resp.setContentType("text/html");
resp.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
resp.addHeader("Content-Length", "" + file.length());
BufferedOutputStream toClient = new BufferedOutputStream(resp.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
logger.debug("-------End to download file[{}]----------", filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isDownload;
}