Is there any way to create a link that downloads a file without the user having to right-click and choose "save linked file as"? Do you need PHP to do this or can it be executed with Javascript only?
Asked
Active
Viewed 2,055 times
1
-
1http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – j08691 Jun 24 '12 at 15:50
4 Answers
0
HTTP Response Headers that identify a file download are sent by the server, and thus cannot be sent using JavaScript. You'll probably need some server-side lines of code to set the correct headers (like PHP's header()
function).

Config
- 1,672
- 12
- 12
0
Here is some example how you can do it with JavaScript but it only works in 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>
Or you can just do document.print()
and save it as a PDF file

itsme
- 575
- 1
- 6
- 15
0
You could solve this with php and the header-function, like this:
<?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);
So your link would point to the php-file instead of the document directly...

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

Ruel
- 15,438
- 7
- 38
- 49