提问人:KucataMeduza 提问时间:1/10/2020 更新时间:1/15/2020 访问量:284
我无法强制下载pdf文件
I can't force download a pdf file
问:
我已经尝试为我的问题寻找解决方案大约 2 天了,但我似乎无法让我的代码工作。我的目标是通过单击按钮下载PDF文件,但我希望对用户隐藏文件的路径。我正在从事的项目正在使用 Kohana(3.3) 框架。我尝试用ajax调用该函数:
public function action_download_pdf()
{
$this->auto_render = false;
if ($this->request->post()) {
$data = $this->request->post();
$file = 'uploads/pdfs_folder/'.$data['pdf_number'].'.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$data['pdf_number'].'.pdf');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
}
我得到状态代码:200 OK,但我只让它显示在开发人员控制台的“预览”选项卡中。
https://i.stack.imgur.com/vyAiK.jpg
我不知道我应该怎么做才能下载它而不是以这种方式显示它?
答:
0赞
Amit Sharma
1/10/2020
#1
这对我来说非常有效。
if ($filename) {
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=".basename($filename));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$filename");
}
评论
0赞
KucataMeduza
1/14/2020
出现相同的符号,但背景为白色。
0赞
Vinit Joshi
1/10/2020
#2
以下代码对我来说效果很好
<?php
if(isset($_REQUEST['path']) && $_REQUEST['path'] != "") {
$file_url = $_REQUEST['path'];
$pdfname = basename ($file_url);
header('Content-Type: application/pdf');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=".$pdfname);
readfile($file_url);
}
?>
在您的代码中,我注意到
header('Content-Type: application/octet-stream');
PHP中的内容类型引用很重要, 它是您要保护的文件的 MIME 类型。 例如,如果您保存了一个 MP3 文件,则需要将 application/pdf 替换为 audio/mpeg。
我希望这对你有所帮助。
谢谢
评论
0赞
KucataMeduza
1/14/2020
我得到了类似的结果。
0赞
KucataMeduza
1/15/2020
#3
所以这就是我解决问题的方式:
我在我的数据库中制作了一个表,在其中生成并保存了一个假数字和一个真实数字。 当我到达带有按钮下载 PDF 的步骤时,我通过该按钮提交一个表单,该按钮会触发控制器中的功能。该函数是我最初发布的代码。我检查了表格中的假号码并得到了真实的号码。
评论