我正在尝试使用openxml创建一个word文档,并使用asp.net在IE中显示它。我有一种奇怪的行为。当我单击表单中的按钮时,假设从新窗口显示word文档。但是,它会在主窗口的底部显示一个错误,说明" filename.docx无法下载"。此时,它在错误旁边提供了一个重试按钮。当我点击重试按钮时,我会调出word文件!
这是启动word文件的JavaScript:
function openWindowWithPostRequest()
{
var winName = '_blank';
var winURL = 'WordPublisher.aspx';
var windowoption = 'resizable=yes,height=600,width=800,location=0,menubar=0,scrollbars=1';
var form = document.createElement("form");
form.setAttribute("method", "get");
form.setAttribute("action", winURL);
form.setAttribute("target", winName);
document.body.appendChild(form);
window.open('', winName, windowoption);
form.target = winName;
form.submit();
document.body.removeChild(form);
//window.close();
return false;
}
以下是提交表单的代码:
<input type="button" value="Create Word" onClick="openWindowWithPostRequest()" />
以下是创建word文档的代码:
protected void Page_Load(object sender, EventArgs e)
{
sendBackWordDocument();
}
public void sendBackWordDocument()
{
using (MemoryStream mem = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem,
WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
Body body = mainPart.Document.Body;
body.Append(new Paragraph(
new Run(
new Text("Hello World!"))));
mainPart.Document.Save();
wordDocument.Close(); // CLOSE DOCUMENT
// Stream it down to the browser
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
mem.Position = 0;
mem.CopyTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
我想知道为什么第一次失败?感谢。
更新#1
我现在已经使用IE,Chrome和FireFox进行了测试。该问题特定于IE。我使用的是IE 9(9.0.8112.16421)。在Chrome和FireFox中,文档首次加载时没有错误。
更新#2
我已经检查了fiddler中的原始数据:
这是第一篇返回错误的帖子:
GET http://localhost:2290/WordPublisher.aspx HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://localhost:2290/WordPublisher.aspx
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Accept-Encoding: gzip, deflate
Host: localhost:2290
Connection: Keep-Alive
这是第二篇文章(点击重试按钮后)正确显示word文档:
GET http://localhost:2290/WordPublisher.aspx HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:2290
Connection: Keep-Alive
答案 0 :(得分:1)
问题已解决!要将docx文件提供给IE 9,请更改以下行:
Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
要:
Response.AppendHeader("Content-Disposition", "inline;filename=HelloWorld.docx");