[Javascript] Show a progress bar while waiting for a download to begin?

Nick Fitzsimons nick at nickfitz.co.uk
Fri Jun 9 11:04:08 CDT 2006


Frank Arensmeier wrote:
> On one of my pages users can download dynamically generated PDF 
> documents by clicking on a normal <a> link. Generating a PDF document 
> would usually take between three and six seconds. When the document is 
> ready, it will be downloaded automatically (the document will not be 
> shown in the browser) by sending an "application/*octet*-*stream*" 
> header. When the server begins outputting the document, it also sends a 
> redirect to the original page.

This won't work because it's not how HTTP works. If you return the 
requested resource (the generated PDF), that's a status 200 response, 
and once you've started that response you can't change it. You can't 
piggyback two responses (a "200 OK" and a "302 Moved Temporarily", which 
is what a redirect is) in one. See

<http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1>

I'm surprised PHP doesn't throw an exception when you try to do this. I 
presume that, having sent response headers such as Content-Type, PHP is 
then ignoring any future attempt to change the HTTP status from 200 to 
302; alternatively it's just going to throw away the generated response 
and only send the redirect. It sound like it's doing the first.

Certainly, no browser is going to know what to do with a response with 
two status lines, as it's a breach of the standard. Browsers (strictly 
speaking, user agents) are, I believe, entitled to simply terminate the 
whole request-response transaction upon receiving something as malformed 
as this would be if it _did_ have two status lines.

Have you had a look at the raw HTTP traffic?

FWIW, when I go to download a file, the browser takes over and displays 
a dialog asking if I want to open or save the file, followed by another 
dialog with a progress bar (IE/Win) or a progress bar in the Download 
Manager dialog (Firefox, Opera, Safari). Any script in your page has no 
access to that information.

If your problem is the few seconds it takes for the server to prepare 
the response, after which the user should see the browser's download 
dialog, you might be able to remove the wait by setting your response 
headers, then flushing the response so far (I'm no PHP expert, but I 
believe the flush() method might do it), and then doing the PDF 
generation. By the time the user has looked blankly at the dialog and 
selected "Save" or "Open" at random (assuming a typical use ;-) your 
server-side code should be a good way along to generating the content.

P.S. See
<http://uk2.php.net/manual/en/function.flush.php>
for details of PHP's flush() function and various gotchas.

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/





More information about the Javascript mailing list