简体   繁体   English

通过Ajax或Javascript强制下载文件

[英]Force a File Download by either Ajax or Javascript

So i have a table listing files, each file's URL is stored as a data attribute on a button. 所以我有一个列出文件的表,每个文件的URL作为数据属性存储在按钮上。 On clicking a button I want to fire a Javascript/Ajax call that will download the file at the URL. 单击一个按钮后,我想触发一个Javascript / Ajax调用,该调用会将文件下载到URL。

Now some caveats, 现在有一些警告,

  1. The file needs to be downloaded via a download dialog or needs to just be added to the Browsers downloads as you would expect. 您需要通过下载对话框来下载文件,或者只需将其添加到浏览器下载中即可。
  2. The request needs to be able to take headers as this is a cross domain request. 该请求必须能够采用标头,因为这是跨域请求。
  3. This needs to work on the main browsers (IE, Chrome, Firefox, Safari) 这需要在主要浏览器(IE,Chrome,Firefox,Safari)上运行

So far I have tried to use XMLHttpRequest: 到目前为止,我已经尝试使用XMLHttpRequest:

e.preventDefault();
var csrftoken = getCookie('csrftoken');
var req = new XMLHttpRequest;
req.open("POST",$(this).data("url"));
req.setRequestHeader("MY HEADER", "HEADER VALUE;");
req.withCredentials = true;
req.send();

I've also tried Ajax GET request (which doesnt force the download) and using the Download attribute on an anchor tag (which doesnt accept headers). 我还尝试了Ajax GET请求(不会强制下载),并在锚标记(不接受标头)上使用Download属性。

Thanks 谢谢

Instead of using anchor tag, which is not cross-browser compliant (apparently, I didn't realize Microsoft was so slow to getting the HTML5 spec.. Not unexpected though) 而不是使用不兼容跨浏览器的锚标记(显然,我没有意识到微软在获得HTML5规范方面是如此缓慢。。

We can utilize the iframe, to avoid redirect and to achieve this effect while maintaining cross-browser compliancy. 我们可以利用iframe避免重定向,并在保持跨浏览器兼容性的同时达到这种效果。

<iframe width="1" height="1" frameborder="0" src="[File location]"></iframe>

As long as the file isn't an .html or some kind of file that can be displayed via browser (.htm, .html, .xhtml, .aspx, etc) then it should download the file. 只要该文件不是.html或可以通过浏览器显示的某种文件(.htm,.html,.xhtml,.aspx等),它都应该下载该文件。

You have to capture the url first, and then: 您必须先捕获URL,然后再捕获:

document.location = 'data:Application/octet-stream,' + encodeURIComponent("http://somedomain.com/somefile.some");

or 要么

window.open("http://somedomain.com/somefile.some");

You don't need headers with this approach. 您不需要使用这种方法的标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM