I am testing a small bit of code to download a file but nothing downloads. I have looked at countless examples (I know this has been asked many times) and from reading these examples this should work. The file definitely exists but no download.
What am I doing wrong?
This is the file (called download.php) in its entirety.
<?php
$file = $_SERVER["DOCUMENT_ROOT"] . "/uploads/test.png" ;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
It is called with a simple js function:
function download() {
$.post("download.php",
function(data, status){
... some stuff will go in here
}
);
}
AJAX doesn’t do downloads. The file contents are in
data
.As @Barmar said, AJAX doesn’t do downloads. A simple solution is use something like
location.href='download.php'
Your browser will trigger the download.So simple – thanks