2011-03-01 30 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

相關問題