我们有时会遇到这样一种情况,当需要下载一个PDF文件时,如果不经处理会直接在浏览器里打开PDF文件,然后再需要通过另存为才能保存下载文件。本文将通过PHP来实现直接下载PDF文件。
实现原理:我们仅仅只需要修改页面HTTP头,把Content来@源gao*daima.com搞@代#码网搞gaodaima代码-Type设置为force-download,问题即可解决。
请看代码:
<BR>forceDownload("pdfdemo.pdf"); <BR>function forceDownload($filename) { <br><br>if (false == file_exists($filename)) { <BR>return false; <BR>} <br><br>// http headers <BR>header('Content-Type: application-x/force-download'); <BR>header('Content-Disposition: attachment; filename="' . basename($filename) .'"'); <BR>header('Content-length: ' . filesize($filename)); <br><br>// for IE6 <BR>if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) { <BR>header('Cache-Control: no-cache, must-revalidate'); <BR>} <BR>header('Pragma: no-cache'); <br><br>// read file content and output <BR>return readfile($filename);; <BR>} <BR>
为了方便,我写了一个函数forceDownload(),然后通过调用该函数即可。