2016-12-02 38 views
1

图像托管在服务器外部,仅下载到用户(客户端)。跨浏览器文件下载按钮点击兼容Chrome和IE?

我试过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

但我仍然感到困惑,使一个简单的脚本。

+0

这不正是你想要的,但你可以使用我的答案的一部分从这里:http://stackoverflow.com/questions/39589917/show-a-progress-bar-for-downloading-file s-using-xhr2-ajax/39599878#39599878(检查'onreadystatechange'里面的javascript代码) – Dekel

+0

你定位哪个IE版本,IE <10 or IE> = 10还是两者兼而有之? – Aruna

+0

@Aruna IE> = 9会很完美,但IE> = 10会有帮助。 – ephramd

回答

2

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

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

GitHub的位置:对于你的情况https://github.com/rndme/download

的示例代码段:

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

 
    if(window.download && url) { 
 
    fileName = fileName || url.split('/').pop().split('?')[0]; 
 
    var ajax = new XMLHttpRequest(); 
 
     \t \t ajax.open('GET', url, true); 
 
     \t \t ajax.responseType = 'blob'; 
 
     \t \t ajax.onload= function(e){ 
 
\t \t \t \t download(e.target.response, fileName, 'application/octet-stream'); 
 
\t \t \t \t }; 
 
     \t \t setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return: 
 
\t \t \t  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>

+0

谢谢!你的例子在这里工作正常,但在我的服务器上它返回以下错误: “Xmlhttprequest无法加载访问控制允许来源标题存在” 是不是不安全启用它? – ephramd

+0

与FF – ephramd

+0

不兼容您只能为特定域启用它,而不是全部。 – Aruna