[英]Javascript download link
有什么方法可以創建一個下載文件的鏈接,而無需用戶右鍵單擊並選擇“將鏈接的文件另存為”? 您需要PHP來做到這一點,還是只能用Javascript執行?
標識文件下載的HTTP響應標頭由服務器發送,因此無法使用JavaScript發送。 您可能需要一些服務器端代碼行來設置正確的標頭(例如PHP的header()
函數)。
這是一些示例,您可以使用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文件
您可以使用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文件而不是文檔。
簡單的PHP:
<?php
header("Content-type: application/octet-stream");
header("Location:filenamegoeshere.txt");
header("Pragma: no-cache");
header("Expires: 0");
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.