2012-06-24 248 views
1

有什么办法可以创建一个链接下载文件,而用户不必右键单击并选择“保存链接文件为”?你需要PHP来做到这一点,还是只能用Javascript来执行?Javascript下载链接

+1

http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – j08691

回答

0

HTTP响应标识文件下载的标题由服务器发送,因此无法使用JavaScript发送。您可能需要一些服务器端代码行来设置正确的头文件(如PHP的header()函数)。

0

下面是一些例子,你如何可以用JavaScript做,但它只能在IE

工作
<html> 
<head> 
<title>xbs_saveas_gt</title> 
<script type="text/javascript"> 
function go_saveas() { 
    if (!!window.ActiveXObject) { 
     document.execCommand("SaveAs"); 
    } else if (!!window.netscape) { 
     var r=document.createRange(); 
     r.setStartBefore(document.getElementsByTagName("head")[0]); 
     var oscript=r.createContextualFragment('<script id="scriptid" type="application/x-javascript" src="chrome://global/content/contentAreaUtils.js"><\/script>'); 
     document.body.appendChild(oscript); 
     r=null; 
     try { 
      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
      saveDocument(document); 
     } catch (e) { 
      //no further notice as user explicitly denied the privilege 
     } finally { 
      var oscript=document.getElementById("scriptid"); //re-defined 
      oscript.parentNode.removeChild(oscript); 
     } 
    } 
} 
</script> 
</head> 
<body> 
<a href="#" onclick="go_saveas();return false">save the document</a><br /> 
</body> 
</html> 

或者你可以做document.print(),并将其保存为PDF文件

0

您可以用解决这个PHP和头功能,这样的:

<?php 
$fileToOpen = "document.txt"; // the file that you want to download 
header("Content-disposition: attachment; filename=$fileToOpen"); 
header("text/plain"); // Depending on the file 
echo file_get_contents($fileToOpen); 

所以,你的链接将指向PHP文件,而不是直接在文档...

0

简单的PHP:

<?php 
    header("Content-type: application/octet-stream"); 
    header("Location:filenamegoeshere.txt"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
?>