2011-03-01 73 views
0

我试图在用户指定时显示在我的网站上下文中显示的PDF页面。我有以下代码:我怎么能写一个PDF到一个asp.net页面?

if (context.User.Identity.IsAuthenticated) 
    { 
     string SampleURL = context.Request.CurrentExecutionFilePath; //CurrentExecutionFilePath; 

     context.Response.Buffer = true; 
     context.Response.Clear(); 
     using (FileStream fs = new FileStream(SampleURL,FileMode.Open)) //System.IO.File.OpenRead(path)) 
     { 
      int length = (int)fs.Length; 
      byte[] buffer; 

      using (BinaryReader br = new BinaryReader(fs)) 
      { 
       buffer = br.ReadBytes(length); 
      } 

      context.Response.Clear(); 
      context.Response.Buffer = true; 
      context.Response.ContentType = "application/pdf"; 
      context.Response.BinaryWrite(buffer); 
      context.Response.End(); 
     } 
    } 
    else 
    { 
     context.Response.Redirect(
      "~/Error/invalid_access.aspx"); 
    } 

唯一的问题是我无法让PATH正常工作。 如果我直接通过URL调用PDF,它将是http://www.abc.com/reports/sample.pdf,但我无法让自己回到那个位置。 我实现了一个HTTPHandler来防止有人转到URL,但现在我需要将文件传回浏览器并写入它。

想法,意见,建议?

编辑: 它的PATH,我无法得到相对网址指向正确的位置。 context.Request.CurrentExecutionFilePath给了我“/www.abc.com/sample_reports/sample.pdf”,但我似乎无法扭转,以便能够打开/阅读它

回答

1

您必须从本地服务器打开它。如果它位于服务器上,你可以做

FileStream fs = new FileStream(Server.MapPath("/example.pdf"),FileMode.Open)

如果你想从你必须先下载PDF的URL加载它。

WebClient client = new WebClient(); 

    // Add a user agent header in case the 
    // requested URI contains a query. 

    client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 

    Stream data = client.OpenRead (args[0]); 
    StreamReader reader = new StreamReader (data); 
    string s = reader.ReadToEnd();` 
+0

实际上它只是Server.MapPath正在把我扔掉。我们有另一个'服务器'命名空间ye'olde intellisense没有给我这个.MapPath – 2011-03-02 01:47:41

+0

只是FYI,很长一段时间扔我的东西是〜符号。 〜在Server.MapPath中不起作用。花了我多年的时间来弄清楚。哈哈 – 2011-03-02 03:11:33

2

你是什么意思的路径?文件的名称?您可以使用Content-Disposition标题来完成此操作。

Response.Addheader "Content-Disposition", "attachment;Filename=WhateverName.pdf" 
+0

+1与被ninja'd几乎相同的信息 – Justin 2011-03-01 22:49:31

0

我会改变一些东西

首先,我可能会考虑切换文件读取的东西更容易,如果它是上下文

context.Response.Clear(); 
context.Response.ClearHeaders(); 
context.Response.Buffer = true; 
context.Response.ContentType = "application/pdf"; 
context.Response.AddHeader("content-disposition","attachment; filename=file.pdf"); 
context.Response.AddHeader("Content-Length", buffer .Length.ToString()); 
context.Response.BinaryWrite(buffer); 
context.Response.Close(); 
context.Response.End(); 
context.Response.Flush(); 
磁盘上的文件

byte[] buffer = File.ReadAllBytes(path); 

现在

上面的代码是否过分矫枉过正?可能,但我发现所有运行在不同浏览器上的杀毒软件都是值得的。

+0

fs.CopyTo(context.Response.OutputStream)可能是最好的办法。不要在内存中保存完整的文件。 – Magnus 2011-03-01 22:54:07

+0

它的路径,我无法得到相对的网址指向正确的位置。 context.Request.CurrentExecutionFilePath给了我“/www.abc.com/sample_reports/sample.pdf”,但我似乎无法扭转,以便能够打开/阅读它 – 2011-03-01 22:56:17

相关问题