2015-06-14 102 views
-2

我一直在使用下面的代码强制图像下载。是的,我知道html5属性,但它不适用于所有浏览器。我的问题似乎是与执行的实际按钮调用该函数强制图像下载jQuery

function SaveToDisk(fileURL, fileName) { 
     // for non-IE 
     if (!window.ActiveXObject) { 
      var save = document.createElement('a'); 
      save.href = fileURL; 
      save.target = '_blank'; 
      save.download = fileName || 'unknown'; 

      var event = document.createEvent('Event'); 
      event.initEvent('click', true, true); 
      save.dispatchEvent(event); 
      (window.URL || window.webkitURL).revokeObjectURL(save.href); 
     } 

     // for IE 
     else if (!! window.ActiveXObject && document.execCommand)  { 
      var _window = window.open(fileURL, '_blank'); 
      _window.document.close(); 
      _window.document.execCommand('SaveAs', true, fileName || fileURL) 
      _window.close(); 
     } 

    // IE 11 
    try { 
     var evt = new MouseEvent('click'); } catch (e) { 
     window.open(fileURL, fileName); 
} 
} 

只是一个测试图像完成后这将是一个photo.jpg。

<button style="width: 100px; height: 50px;" onclick=SaveToDisk(<?php echo $imagelarge[0]; ?>http://lorempixel.com/400/200/);></button> 
+0

jQuery必须在这里做什么? –

回答

0

onclick属性语法错误。它的值必须包含在双倍或单个qoutes中,并包含有效的javascript代码。

<button style="width: 100px; height: 50px;" onclick="SaveToDisk('http://lorempixel.com/400/200/', 'fileName.jpg')">Download</button> 

Here完整的工作示例。

+1

虽然这在理论上可以回答的问题,[这将是优选的](http://meta.stackoverflow.com/q/8259)以包括回答的主要部分在这里,并提供链路参考。 –