简体   繁体   English

为什么下载的文件没有下载而是显示在浏览器中?

[英]Why downloaded file is not downloaded instead it is shown in browser?

I redirect the visitors in my website from page A to page B. In page BI expect users to get the downloaded PDF file (to be downloaded when page B is loading). 我将网站中的访问者从A页重定向到B页。在BI页中,希望用户获得下载的PDF文件(在加载B页时下载)。 I have taken the code from another article (see a previous question answered here ) and my code of page B is the following: 我从另一篇文章中获取了代码(请参见此处回答上一个问题 ),而我的B页代码如下:

<?php
header('Content-Disposition: attachment; filename=nature.pdf');
header('Content-type: application/pdf'); 
$fn=fopen("/wp-content/nature.pdf","r");
fpassthru($fn);
?>

The output is not by opening a download dialog box, instead some unreadable characters are displayed in browser such as the following (I have just picked up a small sample below): 输出不是通过打开下载对话框,而是在浏览器中显示了一些不可读的字符,例如以下内容(我刚刚在下面拾取了一个小示例):

%PDF-1.4 % 3 0 obj <>stream x MK1 o + $zIg& V=T =Xo K i+#V yx3 ඀(BX pW` %PDF-1.4% 3 0 obj <> streamx MK1 o + $ zIg& V =T =Xo K i+#V yx3 ඀ (BX pW`

Server: OS Linux; 服务器:OS Linux; PHP version: 5.2.17 PHP版本:5.2.17

The visitor -> Browser: Firefox; 访问者->浏览器:Firefox; OS: Windows 2000 作业系统:Windows 2000

Is it possible to fail due to the old OS on client side? 是否可能由于客户端的旧操作系统而失败? If not, does anybody know a solution how to force the download? 如果不是,是否有人知道如何强制下载的解决方案? Any help would be highly appreciated. 任何帮助将不胜感激。

Thanks. 谢谢。

Try it with the Content-Length header: 尝试使用Content-Length标头:

ob_clean(); ob_start();
header('Content-Disposition: attachment; filename=nature.pdf');
header('Content-type: application/pdf'); 
header ("Content-Length: ".filesize("/wp-content/nature.pdf"));
readfile("/wp-content/nature.pdf");
exit;

There was a quirk in the really old browsers when Content-disposition was first being introduced, some of the really old browsers wouldn't show the "Save As" dialogue unless it couldn't recognize the type of file you were trying to open. 最初引入Content-disposition时,真正的旧浏览器中存在一个怪癖,某些真正古老的浏览器不会显示“另存为”对话框,除非它无法识别您要打开的文件类型。 Try setting the Content-type to nothing (or something unrecognizable), and see if that'll force the older browser to pop the save-as dialogue. 尝试将Content-type设置为无(或无法识别的内容),然后查看是否会迫使较旧的浏览器弹出“另存为”对话框。

header('Content-type: ');

If that works, then I'd suggest adding in a line of PHP to detect whether or not they're on an old browser before running that line, as modern browsers will use that header to determine what program the file should be opened with. 如果可行,那么我建议添加一行PHP,以在运行该行之前检测它们是否在旧的浏览器上,因为现代浏览器将使用该标头来确定应使用哪个程序打开文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM