强制下载PDF文件,损坏的文件 [英] Force Downloading a PDF file, corrupt file
问题描述
我有一个在SO上出现过很多次的问题,但是我似乎找不到我的解决方案!我正在尝试将pdf文件传递给客户端,而无需在浏览器中打开它,但该文件会下载,但是当我打开它时它已损坏,并且缺少原始文件中的很多字节.我已经尝试了几种下载文件的方法,但是只向您展示我使用的最新方法,希望能得到一些反馈.
I've got a problem that has risen many times on SO, but I can't seem to find the solution to mine! I'm trying to deliver a pdf file to the client without it opening in the browser, the file downloads but it is corrupt when I open it and is missing quite a few bytes from the original file. I've tried several such methods for downloading the file but I'll just show you the latest I've used and hopefully get some feedback.
我也已经在文本编辑器中打开了下载的PDF,并且顶部没有显示任何php错误!
I have also opened the downloaded PDF in a text editor and there are no php errors at the top of it that I can see!
我也知道readfile()快得多,但是出于测试目的,我迫切希望任何东西都能正常工作,所以我使用了while(!feof())方法!
I'm also aware that readfile() is much quicker but for testing purposes I am desperate to get anything working so I used the while(!feof()) approach!
无论如何,代码都是杂乱无章的(取自为什么我下载的文件总是损坏或损坏?):
Anyway enough rambling, heres the code (taken from why my downloaded file is alwayes damaged or corrupted?):
$file = __DIR__ . '/reports/somepdf.pdf';
$basename = basename($file);
$length = sprintf("%u", filesize($file));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $basename . '"');
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: ' . $length);
ob_clean();
set_time_limit(0);
readfile($file);
还要注意的是文件大小的差异:
Also to note was the difference in file size:
Original: 351,873 bytes
Downloaded: 329,163 bytes
推荐答案
确保没有运行任何压缩输出缓冲处理程序,例如ob_gzhandler.我有一个类似的案例,我不得不禁用输出缓冲才能使其正常工作
Make sure you're not running any compression output buffering handlers, such as ob_gzhandler. I had a similar case and I had to disable output buffering for this to work properly
这篇关于强制下载PDF文件,损坏的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!