【问题标题】:Cross Browser file download on a button click compatible with Chrome and IE?单击与 Chrome 和 IE 兼容的按钮单击跨浏览器文件下载?
【发布时间】:2016-12-02 01:38:26
【问题描述】:

图像托管在服务器外部,仅下载给用户(客户端)。

我已经尝试过 HTML5 下载标签,但它在 IE 上效果不佳。

<div style="width:800px; height:457px; background-image:url('http://i.imgur.com/7fypLpI.jpg');"></div>
<a href="http://i.imgur.com/7fypLpI.jpg" download="http://i.imgur.com/7fypLpI.jpg">Download</a>

https://jsfiddle.net/eLpc8d7u/

如何下载文件,例如使用 JavaScript 为任何浏览器下载文件?

我看到了另一个问题:IE download file

但我仍然对制作单个脚本感到困惑。

【问题讨论】:

  • 这不完全是你想要的,但你可以从这里使用我的部分答案:stackoverflow.com/questions/39589917/…(检查onreadystatechange 中的javascript代码)
  • 您的目标是哪个 IE 版本,IE=10 或两者兼有?
  • @Aruna IE>= 9 将是完美的,但使用 IE> = 10 会有所帮助。
  • @ephramd 你可以试试下面的建议吗?

标签: javascript html download


【解决方案1】:

对于跨浏览器下载,包括 IE = 10,您可以使用下面的库,这将为您轻松完成任务。

http://danml.com/js/download.js

GitHub 位置:https://github.com/rndme/download

您的案例的示例代码 sn-p:

function downloadImage(event, url, fileName) {
  event.preventDefault();

  if(window.download && url) {   
     fileName = fileName || url.split('/').pop().split('?')[0];
     var ajax = new XMLHttpRequest();
        		ajax.open( 'GET', url, true);
        		ajax.responseType = 'blob';
        		ajax.onload= function(e){ 
				  download(e.target.response, fileName, 'application/octet-stream');
				};
        		setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
			    return ajax;
  }
}
<script src="http://danml.com/js/download.js"></script>
<div style="width:800px; height:457px; background-image:url('http://i.imgur.com/7fypLpI.jpg');"></div>
<a href="http://i.imgur.com/7fypLpI.jpg" onclick="downloadImage(event, 'http://i.imgur.com/7fypLpI.jpg')">Download with default file name</a><br/>
<a href="http://i.imgur.com/7fypLpI.jpg" onclick="downloadImage(event, 'http://i.imgur.com/7fypLpI.jpg', 'testImage.jpg')">Download with custom file name</a>

【讨论】:

  • 谢谢!您的示例在这里工作正常,但在我的服务器上它返回以下错误:“Xmlhttprequest cannot load no access-control-allow-origin header is present”启用它不是不安全吗?
  • 不兼容FF
  • 您只能为特定域启用它,而不能为所有域启用。
  • 让我检查一下 FF
  • 好的,这是 event 引用的一个小问题,现在为 FF 修复了相同的问题。你现在可以检查吗?
猜你喜欢
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 2016-02-17
相关资源
最近更新 更多