选择'打开'选择Asp.Net下载文件错误在IE9中

时间:2012-03-27 17:18:15

标签: c# asp.net internet-explorer download

我正在使用Response让我的应用程序为用户打开Word文档。如果用户选择保存文件,它会保存文件并且文件看起来在打开时应该如何保存。如果用户选择立即打开文件,则会收到错误消息,指出IE无法打开该文件。如果他们选择“重试”,则MS Word会显示错误消息,指出无法找到该文件。以下是显示我的情况的屏幕截图。此外,这是我必须显示文件的代码:

        this.Context.Response.Clear();
        this.Context.Response.ClearContent();
        this.Context.Response.ClearHeaders();
        this.Context.Response.BufferOutput = true;
        this.Context.Response.ContentType = "application/msword";
        this.Context.Response.AppendHeader("Content-Length", bytes.Length.ToString()); 
        this.Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + "Test Document.doc");
        this.Context.Response.BinaryWrite(bytes);
        this.Context.ApplicationInstance.CompleteRequest();

这是提示用户下载时的屏幕: enter image description here

这是用户选择“打开”后的屏幕 enter image description here

这是用户选择“重试”后的屏幕。这个屏幕即将推出MS Word。 enter image description here

**** **** EDIT 我在网上发现了一些代码,当我调用这个函数时,我尝试测试并发出问题:

    protected void GenerateMsWordDoc()
    {
        string strBody = "<html>" +
            "<body>" + 
                "<div>Your name is: <b>Billy Bob</b></div>" +
                "<table width='100%' style='background-color:#cfcfcf;'><tr><td>1st Cell body data</td><td>2nd cell body data</td></tr></table>" +
                "Ms Word document generated successfully." +
            "</body>" +
            "</html>";
        string fileName = "MsWordSample.doc";
        // You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
        Response.AppendHeader("Content-Type", "application/msword");
        Response.AppendHeader ("Content-disposition", "attachment; filename="+ fileName);
        Response.Write(strBody);
    }

2 个答案:

答案 0 :(得分:1)

您可以发布正在使用的样本数据吗?我尝试在IE9下面的代码工作正常。

this.Context.Response.Clear();
this.Context.Response.ClearContent();
this.Context.Response.ClearHeaders();
this.Context.Response.BufferOutput = true;
this.Context.Response.ContentType = "application/msword";
this.Context.Response.AppendHeader("Content-Length", "12");
this.Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + "Test Document.doc");
this.Context.Response.BinaryWrite(new byte[] { });
this.Context.ApplicationInstance.CompleteRequest();

您最近的代码也正常运行。我正在使用IE9。以下是版本详细信息......

enter image description here

答案 1 :(得分:1)

已知content-disposition的filename参数中的空格会导致不同浏览器版本之间的错误。尝试用双引号括起文件名:

this.Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + "Test Document.doc" + "\"");
相关问题