在没有强制下载的情况下在iframe中显示文档?

时间:2017-05-23 12:03:25

标签: c# html asp.net iframe

浏览各种解决方案以在我的ASP.NET网站(.doc.docx.pdf等)中显示各种文档后,我遇到了一个简单而优雅的解决方案,可以节省我很麻烦:在iframe中显示文档(让浏览器工作)。

<iframe runat="server" id="foo"></iframe>

然后在代码背后:

foo.Attributes["src"] = "http://example.com/docs/koby.pdf";

问题:文档会在浏览器中提示下载,并且不会在其中显示。这是因为我的页面没有声明:

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

但话又说回来,甚至可以将这些标头属性设置为iframe吗? 有人能想出一个解决方案或更好的想法来实现这个目标吗?

1 个答案:

答案 0 :(得分:0)

通过创建处理程序来解决问题:

<%@ WebHandler Language="C#" Class="GetDoc" %>

using System;
using System.Web;

public class GetDoc : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "Application/pdf";
        context.Response.WriteFile("koby.pdf");
        context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

<iframe>来源设为:

foo.Attributes["src"] = "/handlers/GetDoc.ashx";
相关问题