我在按下按钮时即时生成一个文件。我必须遵循以下代码:
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();
我希望在第一次刷新后出现另存为对话框,因为该操作可能需要一段时间。我该怎么办?
<子> 经过一番尝试后,我发现它将缓冲 256 个字符(可通过向客户端发送新字符串 ('x', 256) 来重现)。
最佳答案
我猜您使用的是 Internet Explorer,因为它明确指出它将在 MIME 类型检测期间使用 256 字节的缓冲区:
根据文档: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).
如果前 256 个字节没有被发送来填充缓冲区,它甚至无法开始确定 MIME 类型。确定 MIME 类型后,它与 Windows 注册表 CLSID 相关联并决定应为流显示哪种 UI,从而创建“另存为”对话框。
如评论中所述,使用最广泛的解决方案似乎是用任何字符出现 256 次来填充响应,如: http://encosia.com/easy-incremental-status-updates-for-long-requests/
// Padding to circumvent IE's buffer*
Response.Write(new string('*', 256));
Response.Flush();
我还记得在 IE 友好错误页面上读过类似的内容,可能会受到相同行为的影响,请参阅 http://blogs.msdn.com/b/ieinternals/archive/2010/08/19/http-error-pages-in-internet-explorer.aspx .
编辑:
根据@Ben 的评论,在您的情况下,使用 IE 明确的内容类型,将您的设置为“text/xml”或“application/xml”应该可以解决您的问题。
参见 What Content-Type value should I send for my XML sitemap?差异。
关于c# - 如何让另存为对话框出现 "early"?或者 : How to make Flush() behave correctly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12725699/