PHP:发布下载文件的链接

PHP:发布下载文件的链接

问题描述:

I found this code that allows me to opens a window and allows the user to download a file (download.php)

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

It works well to allow the user to download a file from the server via a pop up window, but I have two issues:

  1. Before executing this block of code, I have some text printing on the screen (browser). However, when the .php file is executed with this block at the very end, nothing prints on the screen, and it goes directly to the download. How do I ensure that things are printed on the browser and then allow the file to be downloaded?

  2. Then, I thought maybe I'll instead insert a link after things are printed, but I'm having trouble getting this to work. When I click on the link to download (href='download.php'), a blank screen is returned and nothing else.

Could someone chime in and help? TIA!

我发现这段代码允许我打开一个窗口并允许用户下载文件(download.php) p>

  header('Content-Description:File Transfer'); 
header('Content-Type:application / octet-stream'); 
header('Content-Disposition:  attachment; filename ='。basename($ file)); 
header('Content-Transfer-Encoding:binary'); 
header('Expires:0'); 
header('Cache-Control:must-revalidate,post  -check = 0,pre-check = 0'); 
header('Pragma:public'); 
header('Content-Length:'。filesize($ file)); 
ob_clean(); 
flush();  
readfile($ file); 
exit; 
  code>  pre> 
 
 

它很适合允许用户通过弹出窗口从服务器下载文件,但我有 两个问题: p>

  1. 在执行这段代码之前,我在屏幕(浏览器)上打印了一些文本。 但是,当最后使用此块执行.php文件时,屏幕上不会打印任何内容,而是直接进入下载。 如何确保在浏览器上打印内容然后允许下载文件? p> li>

  2. 然后,我想也许我会在事后插入一个链接 印刷,但我无法让它工作。 当我点击要下载的链接(href ='download.php')时,会返回一个空白屏幕而没有其他内容。 p> li> ol>

    可能有人 钟声和帮助? TIA! p> div>

You can't return HTML for the browser and a file download from a single page request from the browser. It expects one or the other. You could open a popup window with text, which then does a Javascript redirect to a second PHP script which sends the file.

Anything you echo will be part of your download. You need two separate pages... one to display your text, and another just for the file.

Each page can be parsed in one way only, html/pdf/image/download file etc...
Solution: Do what you want the users see in HTML (link/text what ever) and when they press the download link you open it inside a hidden iframe.

Now, do not come and complain this is not a kick ass way to solve this, we are in 2011, etc
This is the only way (except using Java or Flash) to solve this (Might be html5 will have a nifty solution, but most users browsers do not support this).