我已经构建了一个简单的文件管理器,用户可以下载任何类型的文件,如pdf,word或gif文件。我希望他们所有人都下载文件,而不是在浏览器中查看它。上传的文件名存储在数据库中。
答案 0 :(得分:6)
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
答案 1 :(得分:5)
答案 2 :(得分:2)
正常情况下,在发送文件之前将Content-Disposition
设置为attachment
会强制浏览器下载。
您需要配置您的Web服务器以为文件提供此标头或通过PHP自己发送它们,然后发送特定标头,如:
header('Content-Disposition: attachment; filename=your_file_name.pdf');
请注意第一个解决方案更好,因为您不会因为脚本运行时间过长而导致下载风险被削减(您也可以更改它)。
答案 3 :(得分:0)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/pdf;\n");
$len = filesize($filename);
header("Content-Length: $len;\n");
header("Content-Disposition: attachment; filename=\"downfile.pdf\";\n\n");
echo readfile($filename)
答案 4 :(得分:0)
源自TCPDF 库
的源代码 // download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');
}
header('Content-Description: File Transfer');
if (headers_sent()) {
$this->Error('Some data has already been output to browser, can\'t send PDF file');
}
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
// force download dialog
if (strpos(php_sapi_name(), 'cgi') === false) {
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream', false);
header('Content-Type: application/download', false);
header('Content-Type: application/pdf', false);
} else {
header('Content-Type: application/pdf');
}
// use the Content-Disposition header to supply a recommended filename
header('Content-Disposition: attachment; filename="'.basename($name).'";');
header('Content-Transfer-Encoding: binary');
$this->sendOutputData($this->getBuffer(), $this->bufferlen);
break;
无论如何最重要的部分是
header('Content-Disposition: attachment; filename="'.basename($name).'";');
并注意到字符串中的最后;
,如果没有它,它将无法正常工作