Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a save as dialog appear "early"? Or: How to make Flush() behave correctly?

I'm generating a file on the fly on the event of a button. I have to following code:

Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=Duck.xml");
Response.Write("First part");
Response.Flush();

//simulate long operation   
System.Threading.Thread.Sleep(10000);

//Done
Response.Write("Done");
Response.Flush();
Response.End();

I would like the Save As Dialog to appear after the first flush, because the operation can take a while. How would I go about?

After some playing around I discovered that it will buffer 256 characters (reproducible by sending new string('x', 256) to the client).

like image 530
Kees C. Bakker Avatar asked Nov 12 '22 21:11

Kees C. Bakker


1 Answers

I'm guessing you're using Internet Explorer because it is clearly stated that it will use a 256 bytes buffer during MIME type detection :

Per the documentation : http://msdn.microsoft.com/en-us/library/ms775147(v=vs.85).aspx

A MIME type is ambiguous if it is "text/plain," "application/octet-stream," an empty string, or null

...

FindMimeFromData typically receives three parameters when invoked—the cache file name (assumed to be derived from the associated URL), a pointer to a buffer containing up to the first 256 bytes of the content, and a "suggested" MIME type that typically corresponds to the server-provided MIME type (through the content-type header).

Then it can't even start to determine MIME type if the first 256 bytes are not sent to fill the buffer. When the MIME type is determined, it correlates to the Windows registry CLSID and decide what kind of UI should be shown for the stream, thus creating the "SaveAs" Dialog.

The most widely used solution seems, as said in the comment, to fill the response with 256 occurence of any character as in : http://encosia.com/easy-incremental-status-updates-for-long-requests/

// Padding to circumvent IE's buffer*
Response.Write(new string('*', 256));  
Response.Flush();

I also remember reading something similar on IE friendly error pages that could be affected by the same kind of behavior, see http://blogs.msdn.com/b/ieinternals/archive/2010/08/19/http-error-pages-in-internet-explorer.aspx.

EDIT :

As per @Ben's comment, in your case, with a IE unambiguous content type, setting your to "text/xml" or "application/xml" should solve your problem.

See What Content-Type value should I send for my XML sitemap? for differences.

like image 59
Paciv Avatar answered Nov 15 '22 11:11

Paciv