我已经在SO中找到manyquestionshere关于这个主题,但是它们中的任何一个都可以帮助我解决特定的问题。使用JQuery AJAX和PHP下载PDF文件
我需要发送一个ajax请求到PHP,然后下载一个PDF文件。
这是我的Javascript
$('body').on("click",'.download-file', function(e) {
e.stopPropagation();
var id = $(this).attr('data-id');
$.ajax({
url: 'app/myPage/download',// The framework will redirect it to index.php and then to myPage.class and method dowload
data: id,
type: 'POST',
success: function (return) {
console.log(return);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error... " + textStatus + " " + errorThrown);
}
});
});
这是我的PHP文件:
class myPage{
public function download()
{
$id = $_POST['id'];
$filePath = $this->methodToGetFile($id);
$name = end(explode('/',$filePath));
$fp = fopen($filePath, 'rb');
header("Cache-Control: ");
header("Pragma: ");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($filePath));
header("Content-Disposition: attachment; filename='".$name."';");
header("Content-Transfer-Encoding: binary\n");
fpassthru($fp);
exit;
}
}
通过这种方法,我在控制台中的PDF “印” 像
%PDF-1.5%����1 0 obj<</Type/Catalog/Pages 2 0 R/Lang(pt-BR) /StructTreeRoot 8 0 R/MarkInfo<</Marked true>>>> ...
。
所以,我想知道该怎么做才能打开这个文件并下载它。
在链接的问题我看到一些关于window.location
,但我不知道如何使用它。
我已经试过改变PHP头来尝试强制下载,但没有成功。在这些情况下,我只收到空的JavaScript没有任何反应。这里是修改的标题:
header('Content-Type: application/pdf');//tried with this option
//header('Content-Type: application/octet-stream');// also tried with this other option
header('Content-Disposition: attachment; filename=' . $name);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
是否有一些很好的方法来做到这一点?
header('Content-Type:application/pdf');而不是标题('Content-Type:application/octet-stream'); – Ophitect
我已经试过了。 – James
header('Content-type:application/pdf');你有一个小字母t? – Ophitect