[前端]关于使用ajax下载问题

网友投稿 679 2022-09-02

[前端]关于使用ajax-问题

[前端]关于使用ajax-问题

1.首先,使用js来-是不会保存文件到本地的,因为js不会与硬盘交互,基于安全性原则.

具体原理:

Ajax无法-文件的原因

浏览器的GET(frame、a)和POST(form)请求具有如下特点:

response会交由浏览器处理

response内容可以为二进制文件、字符串等

Ajax请求具有如下特点:

response会交由Javascript处理

response内容仅可以为字符串

因此,Ajax本身无法触发浏览器的-功能。

2.在不使用a标签,纯js下解决办法有三种,一种是直接配置tomcat-,但这种不安全

参考:简单粗暴JavaWeb-第五篇:直接访问HTML、图片

又或者一些.exe文件直接可以通过路径-,是因为服务器配置了Apache文件的local path代理,同时开放了文件-权限

3.第二种是HTML5 a.download结合blob对象进行-

4.第三种是内部用js写一个form或者iframe来提交

这里详说第三种:

定义form:

var form=$("

");//定义一个form表单form.attr("style","display:none");form.attr("target","");form.attr("method","post");form.attr("action","exportData");var input1=$("");input1.attr("type","hidden");input1.attr("name","exportData");input1.attr("value",(new Date()).getMilliseconds());$("body").append(form);//将表单放置在web中form.append(input1);form.submit();//表单提交

iframe:

function download(){ var IFrameRequest=document.createElement("iframe"); IFrameRequest.id="IFrameRequest"; IFrameRequest.src="/test.zip"; IFrameRequest.style.display="none"; document.body.appendChild(IFrameRequest);}

后台:

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; }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:PHP大文件分片上传的实现方法,你会用嘛(php多图片上传)
下一篇:[IOS]如何使用block来实现回调
相关文章

 发表评论

暂时没有评论,来抢沙发吧~