【发布时间】:2021-10-09 16:01:24
【问题描述】:
我有一个 PDF 文件存储在 Wordpress 堆栈的上传目录中。我正在尝试强制浏览器通过 AJAX 下载 PDF。
function get_pdf(){
$file_path = realpath(WP_CONTENT_DIR).'/uploads/pdfs/12345.pdf';
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path, true);
exit;
}
}
当我运行这个函数时,什么也没有发生。我也尝试过这种方法来触发下载:
if (file_exists($file_path)) {
$handle = fopen($file_path, 'rb');
$buffer = '';
while (!feof($handle)) {
$buffer = fread($handle, 4096);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);
}
关于如何调试它以使其正常工作的任何建议?
【问题讨论】:
-
header('Content-Type: application/octet-stream');— PDF 文件的 Content-Type 是application/pdf。如果你知道得更多,你不应该说它只是一些字节。
标签: php wordpress download fopen readfile